1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to cast it directly to a vector?
@iLQ No - a vector is not a POD type.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.