# Converting long to bytes

Having trouble as CRC16 returns a long and I want it to go into an array of two bytes. How do you convert int or long numbers into bytes. Otherwise, does anyone know where to get a 16 bit CRC class that does this.
###### Who is Participating?

x

Commented:
Thank you diakov.
0

Commented:
Hi 'yung',

Try this out. It converts the 64-bit long into 8 bytes and puts it into an array. You can apply it also to 32-bit ints.

byte[] barray = new byte[8];
long L = 0x0A000B000C000D00L;

for (int i = 7; i >= 0; i--)
{
barray[i] = (byte)((L & (byte_mask << (8 * i))) >> (8 * i));
System.out.println(barray[i]);
}

0

Author Commented:
Sorry if this is a dumb question, but what does " 0x0A000B000C000D00L" mean, is this hex? If I'm using the code for an int what would I use?

Ta
0

Commented:
Yes, I used hex just as an example. There you clearly see the bytes. But you can use plain numbers as well. Like
L = 12341235424312L;
In case of int:

byte[] barray = new byte[4];
int iii = 0x0A000D00L; //or something like 341234;

for (int i = 3; i >= 0; i--)
{
barray[i] = (byte)((iii & (byte_mask << (8 * i))) >> (8 * i));
System.out.println(barray[i]);
}
0

Commented:
yung, here is another way of doing that (I prefer it its a bit more elegant):

public static byte[] longToByteArray(long num) {
ByteArrayOutputStream baos;
try {
DataOutputStream dos = new DataOutputStream(baos = new ByteArrayOutputStream());
dos.writeLong(num);
return baos.toByteArray();
} catch( Exception e ) {}
return null;
}

0

Author Commented:
Thanks...both do the trick. I'll finally finish this datacomms assignment. You'll need to post as answrs tho, or else I can't unload the points.

Thanks
0

Commented:
The 'gadio's answer is more elegant and Java style indeed. However, I still prefer the bitwise operations for small values like 1 long.

Say who takes the points.
0

Commented:
yung, wherever the point are going to, learn this pattern of conversion in java, you can use it to change any type to bytes and back this way, even when you don't have a bitwize operations to do that (like doubles and floats).
0

Commented:
Should I toss a coin?

Ok.. here goes

woops.. where'd that coin bounce!!??
DOH!

:)
0

Commented:
as far as I'm concerned points go to 'gadio'.
0

Author Commented:
Hey, both answers were fine and both worked... and gadio, I have studied up on my bitwize operations. Maybe I'll even do well in my exams. Thanks to you both.

I'm giving the points only to gadio because diakov didn't actually post as an answer so I don't know how to do it any other way.
Cheers

yung
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.