如何将二进制数据转换为整数值

时间:2012-04-21 17:55:29

标签: c++ stl integer type-conversion binary-data

问题

将二进制转换为整数表示的最佳方法是什么?

上下文

让我们假设我们有一个包含从外部源(如套接字连接或二进制文件)获取的二进制数据的缓冲区。数据以明确定义的格式组织,我们知道前四个八位字节代表一个无符号的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
  1. 它们是否符合标准,还是使用实现定义的行为?
  2. 哪一个效率更高?
  3. 是否有更好的方式进行转换?

1 个答案:

答案 0 :(得分:3)

你基本上是在询问 endianness 。虽然您的程序可能在一台计算机上运行,​​但它可能不在另一台计如果“定义良好的格式”是网络订单,则有一组标准的宏/函数可以转换为网络订单,也可以转换为特定机器的自然订单。