gpt4 book ai didi

c++ - C位运算题

转载 作者:太空宇宙 更新时间:2023-11-04 06:07:28 25 4
gpt4 key购买 nike

谁能帮我理解这段代码是怎么回事。看起来它正在从一个位数组中生成一个整数。我不确定它是怎么做到的。为什么在OxFF上会有按位&操作?难道这只会产生相同的结果吗?

//first take the first  4 bytes read out of the socket into an array and
//make them a 32 bit integer

long ltemp =0;
long ltemp2 = 0;
ltemp = ltemp | (unsigned char)(analog_val_ptr[0] & 0xff);
ltemp = ltemp << 24;
ltemp2 = ltemp2 | (unsigned char)(analog_val_ptr[1] & 0xff);
ltemp2 = ltemp2 << 16;
ltemp = ltemp2 | ltemp;
ltemp2 =0;
ltemp2 = ltemp2 | (unsigned char)(analog_val_ptr[2] & 0xff);
ltemp2 = ltemp2 << 8;
ltemp = ltemp2 | ltemp;
ltemp = ltemp | (unsigned char)(analog_val_ptr[3] & 0xff);

///then convert that integer into a float, passing

最佳答案

将四个 8 位字节转换为 32 位字节是一种非常冗长的方法。

and0xff 只是确保只使用每个值的低 8 位(0xff == binary 11111111) .

移位(8 的倍数)只是为了让每个字符到正确的位置。

整个事情可以用类似的东西代替:

unsigned long ltemp  = (unsigned char)(analog_val_ptr[0] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[1] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[2] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[3] & 0xff);

或者,或者(假设它们可用),使用正确的工具来完成工作,特别是 htonl()ntohl()

关于c++ - C位运算题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7193182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com