【发布时间】:2012-05-02 22:36:20
【问题描述】:
问题
将二进制转换为整数表示的最佳方法是什么?
上下文
假设我们有一个缓冲区,其中包含从外部源(如套接字连接或二进制文件)获得的二进制数据。数据以明确定义的格式组织,我们知道前四个八位字节表示单个无符号 32 位整数(可能是后续数据的大小)。将这些八位字节转换为可用格式(例如 std::uint32_t)的更有效方法是什么?
示例
这是我迄今为止尝试过的:
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <iostream>
int main()
{
std::array<char, 4> buffer = { 0x01, 0x02, 0x03, 0x04 };
std::uint32_t n = 0;
n |= static_cast<std::uint32_t>(buffer[0]);
n |= static_cast<std::uint32_t>(buffer[1]) << 8;
n |= static_cast<std::uint32_t>(buffer[2]) << 16;
n |= static_cast<std::uint32_t>(buffer[3]) << 24;
std::cout << "Bit shifting: " << n << "\n";
n = 0;
std::memcpy(&n, buffer.data(), buffer.size());
std::cout << "std::memcpy(): " << n << "\n";
n = 0;
std::copy(buffer.begin(), buffer.end(), reinterpret_cast<char*>(&n));
std::cout << "std::copy(): " << n << "\n";
}
在我的系统上,以下程序的结果是
Bit shifting: 67305985
std::memcpy(): 67305985
std::copy(): 67305985
- 它们是否都符合标准,或者它们是否使用实现定义的行为?
- 哪个效率更高?
- 有没有更好的方法来进行这种转换?
【问题讨论】:
-
那里有几个错别字吗?你有
buffer[1]3 次,然后你说std::sort(): 16854009而不是std::copy。 -
你应该使用另一个“测试数组”。使用
{ 0x01, 0x01, 0x01, 0x01 }在转换它时几乎不会失败,因为四个字节是相等的。使用类似{ 0x01, 0x02, 0x03, 0x04 }的东西。使用最后一个数组,只有位移技术才能给出正确的结果(至少在我的 PC 架构上)。 -
@fontanini:{0x1, 0x2, 0x3, 0x4} 的“正确”结果是什么? OP 没有指定字节顺序。如果“定义明确的格式”是小端,则 memcpy 方法是正确的,但位移不是。
-
@GuyGreer 你说得对,我刚刚更新了我的帖子。
-
@DavidHammen 这就是为什么我说位移技术在我的电脑中给出了正确的结果。结果,该数组给了我“16909060”,这是十六进制值
0x01020304,这就是我对转换的期望。 Memcpy/std::copy 给我 "67305985" ->0x04030201.
标签: c++ stl integer type-conversion binary-data