# Thread: Conver long to 8 byte array and back to long

1. ## Conver long to 8 byte array and back to long

I have these two functions to convert one long to a 8 byte array and to convert a byte array to a long, but somethings isn't right..
I think that is my shifts, but I'm not certain.

Code:
```unsigned char* longToByteArray(long value){
unsigned char *b;
b=(unsigned char*)malloc(sizeof(unsigned char)*8);
int i;
for(i = 0; i < 8;i++){
int offset = (8 - 1 - i) * 8;
b[i] = (unsigned char) ((value  >> offset) & 0xFFFFFFFL);

}
return b;
}```
Code:
```long byteArrayToLong(unsigned char* b, int offset) {
long value = 0;
int i;
for (i = 0; i <8; i++) {
int shift = (8 - 1 - i) * 8;
value += (b[i + offset] & 0xFFFFFFFL) << shift  ;
}
return value;

}```
When I convert long x =1111, the bytes are
b[0]=0x0, b[1]=0x0, b[2]=0x4, b[3]=0x57,
b[4]=0x0, b[5]=0x0, b[6]=0x4, b[7]=0x57
and should be:
b[0]=0x0, b[1]=0x0, b[2]=0x0, b[3]=0x0,
b[4]=0x0, b[5]=0x0, b[6]=0x4, b[7]=0x57

If someone can help me, I would be grateful.

2. Be lazy and use a union:
Code:
```    union bl {
unsigned char b[ sizeof( long )];
long l;
};```
Are you sure your long is eight bytes?

Quzah.

3. Whether it really is 8 bytes or not, all of those 8's should be sizeof(long)'s.

4. and mask should be 0xFF

why do you need mask when converting back from array to long?