简体   繁体   English

在C ++中从字节数组检索整数的最佳方法是什么

[英]What is the best way to retreieve an integer from a byte array in C++

Right now I am converting an int to a bytes array this way: 现在,我正在以这种方式将int转换为bytes数组:

int num = 16777215;
char* bytes = static_cast<char*>(static_cast<void*>(&num));

Is this the best way to do it? 这是最好的方法吗?

Also, how can I retrieve the int value from that array? 另外,如何从该数组中检索int值?

If you want the bytes, you are using the wrong cast: 如果需要字节,则使用错误的强制类型转换:

char* bytes = reinterpret_cast<char*>(&num);

Same for the other way around: 在其他方面也一样:

int num = *reinterpret_cast<int*>(bytes);

Note that in general you can't do this, char is special, so you might want to look up aliasing. 请注意,通常您不能这样做,因为char是特殊的,因此您可能需要查找别名。

In response to 回应

Is there any way to cast it directly to a vector? 有什么方法可以将其直接转换为向量吗?

You could do something like this: 您可以执行以下操作:

#include <vector>
#include <cstdint>

template <class T>
std::vector<uint8_t> toByteVector(T value)
{
    std::vector<uint8_t> vec = (std::vector<uint8_t>
                                (reinterpret_cast<uint8_t*>(&value),
                                (reinterpret_cast<uint8_t*>(&value))+sizeof(T))
                                );
    dumpBytes<T>(vec);

    return vec; // RVO to the rescue
}

// just for dumping:
#include <iostream>
#include <typeinfo>
#include <iomanip>

template <class T>
void dumpBytes(const std::vector<uint8_t>& vec)
{
    std::cout << typeid(T).name() << ":\n";
    for (auto b : vec){
        // boost::format is so much better for formatted output.
        // Even a printf statement looks better!
        std::cout << std::hex << std::setfill('0') << std::setw(2)
                  << static_cast<int>(b) << " "
                   ; 
    }
    std::cout << std::endl;
}

int main()
{
    uint16_t n16 = 0xABCD;
    uint32_t n32 = 0x12345678;
    uint64_t n64 = 0x0102030405060708;

    toByteVector(n16);
    toByteVector(n32);
    toByteVector(n64);

    return 0;
}

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

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