我已vector<unsigned char>提交二进制数据.我需要从矢量(2个字节)中取出2个项目并将其转换为整数.如何做到这一点不是用C风格?
你可能会这样做:
vector<unsigned char> somevector;
// Suppose it is initialized and big enough to hold a uint16_t
int i = *reinterpret_cast<const uint16_t*>(&somevector[0]);
// But you must be sure of the byte order
// or
int i2 = (static_cast<int>(somevector[0]) << 8) | somevector[1];
// But you must be sure of the byte order as well
Run Code Online (Sandbox Code Playgroud)
请使用移位运算符/逐位运算.
int t = (v[0] << 8) | v[1];
Run Code Online (Sandbox Code Playgroud)
此处提出的所有基于转换/联合的解决方案都是AFAIK未定义的行为,并且可能在利用严格别名(例如GCC)的编译器上失败.
| 归档时间: |
|
| 查看次数: |
14903 次 |
| 最近记录: |