C位运算题
C Bitwise Operation Question
本文关键字:运算 更新时间:2023-10-16
有人能帮我理解这段代码是怎么回事吗?它看起来像是在从一个位数组中生成一个整数。我不知道它是怎么做到的。为什么会有位元& &;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位字节。
使用0xff
的and
只是确保每个值只使用较低的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()
。
看起来像是在从字节数组中生成一个整数。analog_val_ptr[]
可能是int
或short
值的数组,这段代码被设计成将每个条目视为一个字节。屏蔽是为了防止符号位溢出目标变量。
看起来是独立于端序的转换
var = 0x ? ? ? ? ? ? ? ?
& & & & & & & &
0x 0 0 0 0 0 0 f f
------------------
0 0 0 0 0 0 ? ?
在AND操作之后,将在var & 0xff
中找到低8位。这是一种只剪掉所需部分的方法,屏蔽。
上面的代码只是将4个数组元素的较低的字节粘贴到变量ltemp
中作为长整型。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- GCC本机矩阵运算库
- 位阵列上的快速AND运算
- 字符串中int的加法运算
- 算术运算的结果类似于:C浮点变量中的1/3
- 如何使用OpenMP并行化此矩阵时间矢量运算
- 如何在两个 boost::multi_arrays (C++) 之间执行数学运算?
- 如何在 vtk Poly 数据上进行布尔运算?
- MSVC 无法根据模板参数进行数学运算,这是一个错误吗?
- 避免指针运算,修复叮当整齐错误
- 使用双精度的浮点运算
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 更快的C++算术运算
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?
- 为什么循环体中的一个基本算术运算执行得比两个算术运算慢
- 两个字符串之间的数学运算
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 何时使用按位运算而不是算术替代方法?
- Arduino 上数学运算的计时速度 - 异常
- 如何使用按位运算将随机uint64_t转换为范围 (0, 1) 的随机双精度