c++ - 将 char* 数组合并到 uint16_t

标签 c++ arrays binary bitwise-operators

我正在尝试将一个 char* 数组合并到一个 uint16_t 中。到目前为止,这是我的代码:

char* arr = new char[2]{0};
arr[0] = 0x0; // Binary: 00000000
arr[1] = 0xBE; // Binary: 10111110

uint16_t merged = (arr[0] << 8) + arr[1]; 
cout << merged << " As Bitset: " << bitset<16>(merged) << endl; 

我原以为 merged0xBE,或者是二进制 00000000 10111110

但是应用程序的输出是:

65470 As Bitset: 1111111110111110

在下面的描述中,我从左到右阅读位

所以arr[1]在正确的位置,也就是后8位。 然而,前 8 位被设置为 1,这是不应该的。

此外,如果我将值更改为

arr[0] = 0x1; // Binary: 00000001
arr[1] = 0xBE; // Binary: 10111110

输出是:

0000000010111110

同样,arr[1] 位于正确的位置。但是现在前 8 位是 0,而前 8 位的最后一位应该是 1

基本上我不想做的是将 arr[1] 附加到 arr[0] 并将新数字解释为一个整体。

最佳答案

也许 char在你的情况下是签名类型,你左移 0xBE vhich 被解释为带符号的负值( -66 在可能的情况下为 two's complement )。

根据标准,这是未定义的行为。在实践中,它通常会导致扩展符号位,从而导致前导位。

3.9.1 Fundamental types
....

It is implementationdefined whether a char object can hold negative values.


5.8 Shift operators
....

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1×2E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

关于c++ - 将 char* 数组合并到 uint16_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519334/

相关文章:

c++ - 是否可以通过模板类型更改静态 const 类成员的值?

arrays - 如何在 MATLAB 中合并结构体/结构体数组?

c# - 高效获取数组子集

java - 如何从 String 创建 String[] 数组?

c++ - 将两个列表合并为一个列表

c++ - 在受控情况下更改基类变量的类型?

parsing - scala 的解析器组合器可以解析二进制文件吗?

java - 移位时字节值的内存分配

可以将二进制文件中的字符串替换为不同但长度相同的字符串的 Ruby 脚本?

c++ - 您建议使用什么用于前馈神经网络的 C++?