c ++将QWORD十六进制拆分为较小的变量

时间:2017-01-05 16:26:09

标签: c++

我有一个unsigned long long,我想将它拆分成更小的字节。 e.g。

unsigned long long TEST = 0x465958432E1F0199;

我希望它分成如下字符。 char TEST2 equal to 0x46, TEST3 equal to 0x59, TEST4 equal to 0x58,等等。我该怎么做?

3 个答案:

答案 0 :(得分:1)

使用指针就可以了。

template <typename T>
std::vector<uint8_t> iterateOverBytes(const T& var) {
    std::vector<uint8_t> toReturn;

    for(auto i = 0u; i < sizeof(var); ++i) {
        toReturn.push_back(reinterpret_cast<const uint8_t*>(&var)[i]);
    }

    return toReturn;
}

sizeof(var)以字节为单位返回var的大小,您可以使用指向var的指针,类似于大小为sizeof(var)的字节数组。

现在简单的循环打印数字完成代码:

for(const auto& byte: iterateOverBytes(TEST)) {
    std::cout << std::hex << int(byte) << std::endl;
}

答案 1 :(得分:0)

一个完全不需要演员表的解决方案怎么样? (;

unsigned long long TEST = 0x465958432E1F0199;
uint8_t elements[sizeof(TEST)];
memcpy(elements, &test, sizeof(elements));

答案 2 :(得分:0)

使用重铸指针读取整数值的每个字节是不可移植的,因为系统可以使用不同的方式对构成整数值的组件字节进行排序。 Big-endian系统将最重要的字节放在内存中,而little-endian系统从最低位字节开始。

为了便于处理,请使用位移运算符将所需字节放在派生整数值的最低位置,然后将结果转换为字节大小的整数类型(如uint8_t)。

#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdint>

int main() {
    const unsigned long long word = 0x465958432E1F0199ull;
    // scan through all bytes, adding each one to a vector
    // most significant byte first
    std::vector<std::uint8_t> bytes;
    for(auto i=sizeof(word)-1; i+1; --i) {
        const auto b = static_cast<std::uint8_t>(word >> i*8);
        bytes.push_back(b);
    }
    // Dump vector of bytes as 2-digit hex values
    std::cout << std::hex << std::setfill('0');
    for(auto b : bytes) {
        std::cout << std::setw(2) << static_cast<unsigned>(b) << ' ';
    }
    std::cout << '\n';
}

输出

46 59 58 43 2e 1f 01 99