Daniel Cardenas
Daniel Cardenas

Reputation: 2984

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 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?

Upvotes: 1

Views: 94

Answers (2)

frasnian
frasnian

Reputation: 2003

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;
}

Upvotes: 1

Barry
Barry

Reputation: 303007

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.

Upvotes: 1

Related Questions