Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Convert unsigned long long int into vector<char> and vice versa

Can anyone tell me how to convert unsigned long long int into vector and vice versa.

For converting from unsigned long long int to vector, I tried the following:

unsigned long long int x;
vector<char> buf(sizeof(x));
memcpy( &buf[0], &x, sizeof( x ) );

When I tested for x = 1234567890, it failed. But when I tried it for smaller values of x (say 1-100), it works...

For converting vector to unsigned long long int, I used:

   unsigned long long int =  (unsigned long long int)buf[0];

Can anyone tell me how to do it.

like image 856
veda Avatar asked Dec 10 '22 03:12

veda


2 Answers

Just remember that copying bytes around won't be cross-platform portable. Your memcpy looks fine, so why not re-create that on the way back out? What you've written simply takes the first byte of the vector and converts it to an unsigned long long which explains why it works for small numbers.

Try this instead to get the value back out of the vector:

unsigned long long int x;
memcpy(&x, &buf[0], sizeof(x));
like image 138
Mark B Avatar answered Jan 30 '23 06:01

Mark B


Instead of memcpying directly into the vector you can use std::vector::assign to perform 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
like image 38
Praetorian Avatar answered Jan 30 '23 06:01

Praetorian