无符号移位和环将产生负值
unsigned int - shifting and oring creates negative value
本文关键字:无符号 更新时间:2023-10-16
当我从文件中读取原始字节时,我正在读取wav
文件的头并使用<<
(左移)和|
(或)填充我的类成员。现在,巧合的是,我有以下情况
其中uBytesPerSecond
是unsigned
类型,data
是char*
类型,所以我可以使用std::fstream::read
。
现在当我在调试器
中创建uBytesPerSecond
时this->uBytesPerSecond |= data[0x1F]; //0x00 ->uBytesPerSecond = 0x00000000
this->uBytesPerSecond <<= 8; // ->uBytesPerSecond = 0x00000000
this->uBytesPerSecond |= data[0x1E]; //0x02 ->uBytesPerSecond = 0x00000002
this->uBytesPerSecond <<= 8; // ->uBytesPerSecond = 0x00000200
this->uBytesPerSecond |= data[0x1D]; //0xb1 ->uBytesPerSecond = 0xffffffb1 !!!
this->uBytesPerSecond <<= 8; // ->uBytesPerSecond = 0xffffb100
this->uBytesPerSecond |= data[0x1C]; //0x10 ->uBytesPerSecond = 0xffffb110
本例中的预期输出是uBytesPerSecond = 0x00002b110
。请告诉我发生了什么事,我该如何解决。
我使用的是MSVC2012
和Windows 8,这是一个VC++-Console
应用程序
问题是,对于您的平台char
是有符号类型。因此,对于or操作,包含的值将被符号扩展到32位,为data[0x1D]
提供0xffffffb1
。
要解决这个问题,只需将data
的类型更改为unsigned char*
。
Edit:如评论中所述,问题的另一种解决方案是显式地用0xFF
: this->uBytesPerSecond |= data[0x1F] & 0xFF
等掩码操作数。
为什么不使用联合而不是使用位或和移位呢?就像
union ByteWord
{
unsigned int word;
char bytes[sizeof(unsigned int)];
}
那么你可以直接写
ByteWord data;
myStream.read(data.bytes, sizeof(unsigned int));
this->uBytesPerSecond = myStream.word;
如果需要字节交换,请使用ntohl(myStream.word)
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 获取隐式转换溢出从无符号到已签名的警告
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- C4018:类内有符号、无符号不匹配
- C++无符号短裤的划分导致 int
- 库特无符号字符