写入有符号整数,就好像在C ++中是无符号整数一样 [英] Writing to a signed integer as if it is unsigned in C++

查看:62
本文介绍了写入有符号整数,就好像在C ++中是无符号整数一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

reinterpret_cast 是否安全,这是最好的方法吗?

Is reinterpret_cast safe for this, and is it the best way to do this?

例如,在下面的代码中,我有一个名为 ibytestream 的类,该类允许从中读取 uint16_t s和 int16_t s它. ibytestream :: next vector< unsigned char> :: iterator .

For example, in the code below, I have a class called ibytestream, which allows the reading of uint16_ts and int16_ts from it. ibytestream::next is a vector<unsigned char>::iterator.

inline ibytestream& operator>>(ibytestream& stream, uint16_t& data) {
    data = 0;
    data |= *stream.next++;
    data <<= 8;
    data |= *stream.next++;
    return stream;
}

inline ibytestream& operator>>(ibytestream& stream, int16_t& data) {
    return stream >> reinterpret_cast<uint16_t&>(data);
}

我不想复制将字节转换为整数的代码,因此我对签名版本使用了 reinterpret_cast 来重用未签名版本中的代码.它可以在我的机器上正常工作,但是通常可以在其他现代机器上工作吗?

I don't want to duplicate the code for converting the bytes to an integer, so I used reinterpret_cast for the signed version to reuse the code from the unsigned version. It works fine on my machine, but will it work in general on other modern machines?

推荐答案

是的,这很安全.

该标准的三个部分适用于此确定:

Three parts of the standard apply to make this determination:

  1. 有符号和无符号类型的对齐要求相同
  2. 允许在指向具有相同对齐要求的类型的指针之间进行指针转换
  3. 在glvalues之间执行强制转换时,如果相应指针之间的强制转换有效,则强制转换有效.

对于每种标准有符号整数类型,都有一个对应的(但不同的)标准无符号整数类型: unsigned char unsigned short int unsignedint unsigned long int ,和 unsigned long long int ,它们各自占用相同的存储空间,并具有相同的对齐要求.

For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, and unsigned long long int, each of which occupies the same amount of storage and has the same alignment requirements.

可以将对象指针显式转换为其他类型的对象指针.将类型为指向T1的指针"的prvalue转换为指向T2的指针"的类型(其中T1和T2是对象类型,并且T2的对齐要求不严格于T1的对齐要求),并返回其原始类型将产生原始值.指针值.

An object pointer can be explicitly converted to an object pointer of a different type. Converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value.

如果可以使用reinterpret_cast将类型指向T1的指针"显式转换为类型指向T2的指针",则可以将类型T1的glvalue表达式强制转换为对T2的引用"类型.结果参考到与源glvalue相同的对象,但是具有指定的类型.

A glvalue expression of type T1 can be cast to the type "reference to T2" if an expression of type "pointer to T1" can be explicitly converted to the type "pointer to T2" using a reinterpret_cast. The result refers to the same object as the source glvalue, but with the specified type.

这篇关于写入有符号整数,就好像在C ++中是无符号整数一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆