简体   繁体   English

将整数转换为 4 字节未编码的字符向量(按大端字节顺序)

[英]Convert Integer to 4 byte ungisned char vector (in Big endian byte order)

Suppose, I wanted to write decimal 31 in a binary file (which is already loaded into vector) in 4 bytes so I have to write as 00 00 00 1f, but I don't know how to convert decimal number in hex string (of 4 bytes)假设,我想在 4 个字节的二进制文件(已经加载到向量中)中写入十进制 31,所以我必须写为 00 00 00 1f,但我不知道如何将十进制数转换为十六进制字符串(的4字节)

So, expected hex in vector of unsigned char is:因此,无符号字符向量中的预期十六进制是:

0x00 0x00 0x00 0x1f // int value of this is 31

To do this I tried following:为此,我尝试了以下操作:

std::stringstream stream;
stream << std::setfill('0') << std::setw(sizeof(int) * 2) << std::hex << 31;
cout << stream.str();

Output:输出:

0000001f

Above line of code gives output in string format but I want it into vector of unsigned char in format of '0x', so my output vector should have elements after conversion as 0x00 0x00 0x00 0x1F.上面的代码行给出了字符串格式的输出,但我希望它以'0x'格式的无符号字符向量,所以我的输出向量在转换后应该有元素为0x00 0x00 0x00 0x1F。

Without bothering with endianness you could copy the int value into a character buffer of the appropriate size.无需担心字节顺序,您可以将int值复制到适当大小的字符缓冲区中。 This buffer could be the vector itself.这个缓冲区可以是向量本身。

Perhaps something like this:也许是这样的:

std::vector<uint8_t> int_to_vector(unsigned value)
{
    // Create a vector of unsigned characters (bytes on a byte-oriented platform)
    // The size will be set to the same size as the value type
    std::vector<uint8_t> buffer(sizeof value);

    // Do a byte-wise copy of the value into the vector data
    std::memcpy(buffer.data(), &value, sizeof value);

    return buffer;
}

The order of bytes in the vector will always in the host native order.向量中的字节顺序将始终按主机本机顺序排列。 If a specific order is mandated then each byte of the multi-byte value needs to be copied into a specific element of the array using bitwise operations ( std::memcpy can't be used).如果强制要求特定顺序,则需要使用按位运算将多字节值的每个字节复制到数组的特定元素中(不能使用std::memcpy )。

Also note that this function will break strict aliasing if uint8_t isn't an alias of unsigned char .另请注意,如果uint8_t不是unsigned char的别名,则此函数将破坏严格别名。 And that uint8_t is an optional type, there are platforms which doesn't have 8-bit entities (though they are not common).并且uint8_t是可选类型,有些平台没有 8 位实体(尽管它们并不常见)。


For an endianness-specific variant, where each value of a byte is extracted one by one and added to the vector, perhaps something like this:对于特定于字节序的变体,其中一个字节的每个值都被一个一个地提取并添加到向量中,可能是这样的:

std::vector<uint8_t> int_to_be_vector(unsigned value)
{
    // Create a vector of unsigned characters (bytes on a byte-oriented platform)
    // The size will be set to the same size as the value type
    std::vector<uint8_t> buffer(sizeof value);

    // For each byte in the multi-byte value, copy it to the "correct" place in the vector
    for (size_t i = buffer.size(); i > 0; --i)
    {
        // The cast truncates the value, dropping all but the lowest eight bits
        buffer[i - 1] = static_cast<uint8_t>(value);
        value >>= 8;
    }

    return buffer;
}

Example of it working它的工作示例

You could use a loop to extract one byte at a time of the original number and store that in a vector.您可以使用循环一次提取原始数字的一个字节并将其存储在向量中。

#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>

using u8 = std::uint8_t;
using u32 = std::uint32_t;

std::vector<u8> GetBytes(const u32 number) {
    const u32 mask{0xFF};
    u32 remaining{number};

    std::vector<u8> result{};
    while (remaining != 0u) {
        const u32 bits{remaining & mask};
        const u8 res{static_cast<u8>(bits)};
        result.push_back(res);
        remaining >>= 8u;
    }
    std::reverse(std::begin(result), std::end(result));
    return result;
}

int main() {
    const u32 myNumber{0xABC123};
    const auto bytes{GetBytes(myNumber)};
    std::cout << std::hex << std::showbase;
    for (const auto b : bytes) {
        std::cout << static_cast<u32>(b) << ' ';
    }
    std::cout << std::endl;
    return 0;
}

The output of this program is:这个程序的输出是:

0xab 0xc1 0x23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM