加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在char数组和掩码中使用int而不是char

发布时间:2020-12-16 07:32:01 所属栏目:百科 来源:网络整理
导读:在所示的位移示例中 here: unsigned long int longInt = 1234567890; unsigned char byteArray[4]; // convert from an unsigned long int to a 4-byte array byteArray[0] = (int)((longInt 24) 0xFF) ; byteArray[1] = (int)((longInt 16) 0xFF) ; byteAr
在所示的位移示例中
here:

unsigned long int longInt = 1234567890;
 unsigned char byteArray[4];

 // convert from an unsigned long int to a 4-byte array
 byteArray[0] = (int)((longInt >> 24) & 0xFF) ;
 byteArray[1] = (int)((longInt >> 16) & 0xFF) ;
 byteArray[2] = (int)((longInt >> 8) & 0XFF);
 byteArray[3] = (int)((longInt & 0XFF));

三个问题:

>为什么它(int)而不是(unsigned char)?我用unsigned char尝试了它,似乎编译得很好.
>需要0XFF吗?是不是新位移入了0因为维基百科说C使用逻辑移位和0中的逻辑移位移位? (编辑:至少在>> 24上没有必要吗?)
>我不能只使用memcpy()将longInt复制到unsigned char缓冲区吗?是不是因为Endianness的问题?还有其他原因吗?

解决方法

1.

((longInt>> 24)& 0xFF)表达式的类型为unsigned long int.使用强制转换为int,表达式首先转换为int,然后转换为unsigned char.如果不转换为int,则表达式不会首先转换为int.这两种情况没有区别,演员阵容是多余的.

2.

0xff不是必需的.转换为unsigned char实际上执行相同的操作.

3.

您可以使用memcpy,但它不可移植,因为它取决于系统的字节顺序.如果系统是大端或小端,它将给出不同的结果,而按位移位解将给出相同的结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读