0

How do I copy an int (or any other data type) byte-by-byte to a vector<unsigned char>?

int x = 10;
std::vector<unsigned char> byteArray(sizeof(int));
std::copy(byteArray.begin(), byteArray.end(), x); // how do I use x here?

If not possible with std::copy, can it be done with memcpy or any other technique?

pinbox
  • 83
  • 1
  • 7
  • 3
    `vector byteArray[sizeof(int)]` is an array of `std::vectors` – Rabbid76 Jun 19 '17 at 04:42
  • Yes sorry I meant to initialize it with `sizeof(int)` elements – pinbox Jun 19 '17 at 04:51
  • 2
    try memcpy(byteArray.data(), &x, sizeof(int)); – Daniel Jun 19 '17 at 04:56
  • @Daniel wow, that worked. Thanks! – pinbox Jun 19 '17 at 05:00
  • To confirm: are you attempting to decompose an `int` into a vector of bytes that represent its value? And if so, do you care about little endian vs. big endian representation? – Disillusioned Jun 19 '17 at 05:01
  • @CraigYoung I don't care about the representation, I need to calculate a hash value based on it's bytes. – pinbox Jun 19 '17 at 05:04
  • Then I expect you probably should care. Endianness is about the order of the bytes in an integer. Any hash that function that is not affected by the order of the bytes is a pretty weak hash. – Disillusioned Jun 19 '17 at 05:07
  • 1
    I see your point. The hash I'm using is a non-cryptographic hash meant only for hash-based lookups. The issue is the data type can be any data type. That means I need to make separate byte conversions for int, long, char *, etc. which might not be worth the effort. Also, I'm not looking to make the code portable. – pinbox Jun 19 '17 at 05:14
  • gotcha, since hashes will be internal, byte-order will be consistent within a system - whatever it may be. – Disillusioned Jun 19 '17 at 05:16

1 Answers1

0

Problem you are dealing with is called serialization. Solution with memcpy is 'crude but effective' so if your project is small I think it is OK to use it. Otherwise I recommend looking at some solutions, for example, provided in boost or Qt. This will provide you with generic interface for multiple data types.

How do you serialize an object in C++?