我可以对整个 char 数组使用按位吗?

问题描述 投票:0回答:2

我可以对整个 char 数组使用按位吗?

工作示例:

   unsigned int aNumInt= 0xFFFF; //1111111111111111
   aNumInt = aNumInt << 8; // 1111111100000000

是否可以对整个字符数组执行相同的操作?

不是工作示例:

     unsigned char aCharInt[2]={0xFF,0xFF}; //1111111111111111
     aCharInt = aCharInt << 8; //<-- this does not work.. using it as an example
     // 1111111100000000
  

or do 是唯一的方法是逐字节进行

aCharInt[1] = aCharInt[1] << 8;
memcpy

arrays c pointers bit-manipulation bitwise-operators
2个回答
1
投票

在 C 语言中,您很少能同时操作数组的所有元素。少数例外之一是,如果您有一个属于结构体一部分的数组;然后您可以复制数组的元素作为结构赋值的一部分。但这不适用于这里。

必须依次对每个元素应用移位运算或其他按位运算符。


0
投票

此代码将如您所期望/想要的那样。

免责声明:此代码仅用于教育目的!我不推荐 此类事情的日常实践,或在任何关键代码场景中的使用。

unsigned long aNumInt= 0xFFFF; //1111111111111111
unsigned char aCharInt[2]={0xFF,0xFF}; //1111111111111111
unsigned long aCastInt;

aNumInt = aNumInt << 8; // 1111111100000000

/* Cast the char array to a pointer of type unsigned long, then 
** dereference the pointer to obtain the numeric value and finally 
** shift left 8 */
aCastInt = *((unsigned long*)aCharInt) << 8;

printf("aNumInt:  %lu\n", aNumInt );
printf("aCastInt: %lu \n", aCastInt );

输出: 号码:16776960 aCastInt:16776960

再次强调:不建议日常使用代码。这只是为了演示 C 语言的强大(或灵活性)。

© www.soinside.com 2019 - 2024. All rights reserved.