CSDN博客

img zykaka

convert an int into a byte array

发表于2004/9/15 23:30:00  430人阅读

I have been working on transmitting JPEG's through sockets.
In order to read each picture, I needed to know the number of bytes. I too had to create int to byte[] and byte[] to int.
Here is the code:
[code]
/**
* @param ba
* @return
*/
private int getIntFromByteArray(byte[] ba) {
int i;
if (ba[0] < 0)
i = ba[0] + 256;
else
i = ba[0];
i <<= 8;
if (ba[1] < 0)
i += ba[1] + 256;
else
i += ba[1];
i <<= 8;
if (ba[2] < 0)
i += ba[2] + 256;
else
i += ba[2];
i <<= 8;
if (ba[3] < 0)
i += ba[3] + 256;
else
i += ba[3];
return i;

}
/**
* @param i
* @return
*/
private byte[] getIntToByteArray(int v) {

byte b[] = new byte[4];
int i, shift;

for(i = 0, shift = 24; i < 4; i++, shift -= 8)
b
= (byte)(0xFF & (v >> shift));

return b;


}
[/code]
0 0

相关博文

我的热门文章

img
取 消
img