如何将二进制数据转换为整数值
How to convert binary data to an integral value
问题
将二进制转换为其积分表示的最佳方法是什么?
上下文
假设我们有一个缓冲区,其中包含从外部源(如套接字连接或二进制文件)获得的二进制数据。数据以明确定义的格式组织,我们知道前四个八位字节表示单个无符号 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
- 它们是否都符合标准,或者它们是否使用实现定义的行为?
- 哪一个更有效率?
- 有没有一种进行这种转换的贝特方法?
你本质上是在问字节序。虽然您的程序可能在一台计算机上运行,但它可能无法在另一台计算机上运行。如果"定义良好的格式"是网络顺序,则有一组标准的宏/函数可以转换为特定机器的网络顺序和自然顺序。
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常