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

How to convert binary data to an integral value

本文关键字:整数 转换 数据 二进制      更新时间:2023-10-16

问题

将二进制转换为其积分表示的最佳方法是什么?

上下文

假设我们有一个缓冲区,其中包含从外部源(如套接字连接或二进制文件)获得的二进制数据。数据以明确定义的格式组织,我们知道前四个八位字节表示单个无符号 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. 有没有一种进行这种转换的贝特方法?

你本质上是在问字节序。虽然您的程序可能在一台计算机上运行,但它可能无法在另一台计算机上运行。如果"定义良好的格式"是网络顺序,则有一组标准的宏/函数可以转换为特定机器的网络顺序和自然顺序。