## Byte Number Conversion

For a project I'm working on these days I was forced to convert raw byte to several numerical values ( to and from binary format).

Bytes are represented in C/C++ as  unsigned char, and std::string are often used as byte buffer as well as old well known raw arrays. I wrote a simple struct that relieve the pain in performing such conversions. It exposes two functions: fromBytes and toBytes.fromBytes takes an additional boolean parameter that takes care of different endianness.

```/*
Author: Davide Spataro 2016

Converts byte buffer to type T
*/
typedef unsigned char byte;

template <class T>
struct converter{

static const size_t size = sizeof(T);

union conv{
T value;
byte bytes[ sizeof( T ) ];
} c ;

T fromBytes( const  byte *bytes, bool endianness = false){

if(endianness)
#pragma unroll
for(int i=0;i<size;i++)
c.bytes[size-1-i] = bytes[i];
else
#pragma unroll
for(int i=0;i<size;i++)
c.bytes[i] = bytes[i];

return c.value;
}

byte* toBytes(const T& value,bool endianness = false){
c.value =value;
if(endianness)
reverse();
return c.bytes;
}

void reverse(){
#pragma unroll
for(int i=0;i<size/2;i++){
byte tmp = c.bytes[i];
c.bytes[i]=c.bytes[size-1-i];
c.bytes[size-1-i] = tmp;
}

}

};

template<class T>
void printHex(const T& key, size_t size){
std::cout.setf(std::ios::hex, std::ios::basefield);
for (int i = 0; i < size; i++){ if (i > 0) printf(":");
printf("%02X", (unsigned char)key[i]);

printf("\n");
}

```

Usage is very simple: let's say for instance you have the following 8 bytes into an unsigned long long

00:00:00:00:00:00:00:5E

```
converter<int64_t> c;
//binary value is 00:00:00:00:00:00:00:5E (8 bytes)