C ++: convert unsigned long long int to <char> vector and vice versa
Can someone tell me how to convert unsigned long long int to a vector and vice versa.
To convert from unsigned long long int to a vector, I tried the following:
unsigned long long int x; vector<char> buf(sizeof(x)); memcpy( &buf[0], &x, sizeof( x ) ); When I tested x = 1234567890, it failed. But when I tried it for smaller x values ββ(say 1-100), it works ...
To convert a vector to an unsigned long long int, I used:
unsigned long long int = (unsigned long long int)buf[0]; Can anyone tell me how to do this.
Just remember that copying bytes around will not be cross-platform. Your memcpy looks great, so why not recreate this on the way back? What you wrote just takes the first byte of the vector and converts it to an unsigned long long , which explains why it works for small numbers.
Try returning the value from the vector instead:
unsigned long long int x; memcpy(&x, &buf[0], sizeof(x)); Instead of memcpy directly into a vector, you can use std::vector::assign to do the copying.
#include <iostream> #include <vector> int main() { unsigned long long int x = 0x0807060504030201; std::vector<char> v; v.assign( reinterpret_cast<char *>( &x ), reinterpret_cast<char *>( &x ) + sizeof( x ) ); for( auto i = v.begin(); i != v.end(); ++i ) { std::cout << std::hex << static_cast<int>( *i ) << ' '; } std::cout << std::endl; // To convert back auto y = *reinterpret_cast<unsigned long long int *>( &v[0] ); std::cout << "y = " << std::hex << std::showbase << y << std::endl; return 0; } Output:
1 2 3 4 5 6 7 8 y = 0x807060504030201 You should change your last line:
memcpy( &buf[0], reinterpret_cast<char*>(&x), sizeof( x ) ); Change I said stupidity, this line is fine, but your reverse conversion is bad - you are converting a value instead of a pointer:
unsigned long long int val = *reinterpret_cast<unsigned long long int*>(&buf[0]);