开发者

Converting int to byte in Android

Actually I need to transfer the integer value along with the bitmap via bluetooth.. Now开发者_StackOverflow中文版 my problem is I need to transfer the integer as single byte value.. Is tat possible to convert int as single byte value.. and retrieve it as a integer there... I tried byteValue() and the casting thing but its not usefull.. If my approach is right just help me out with this or say some other way.

(Each time when I am using casting then it's returning as 65535)


What about this?

public static byte[] intToByteArray(int a)
{
    byte[] ret = new byte[4];
    ret[3] = (byte) (a & 0xFF);   
    ret[2] = (byte) ((a >> 8) & 0xFF);   
    ret[1] = (byte) ((a >> 16) & 0xFF);   
    ret[0] = (byte) ((a >> 24) & 0xFF);
    return ret;
}

and

public static int byteArrayToInt(byte[] b)
{
    return (b[3] & 0xFF) + ((b[2] & 0xFF) << 8) + ((b[1] & 0xFF) << 16) + ((b[0] & 0xFF) << 24);
}


If you're completely sure, that your int variable contains a byte value [-128; 127] then it should be as simple as:

int i = 100; // your int variable
byte b = (byte) i;


A single byte (8 bits) can only contain 2^8 unsigned integers, i.e [0, 255]. For signed you loose the first bit and the range becomes [-128, 127]. If your integer fits then a simple cast should work.


for 0-255 numbers.

int i = 200; // your int variable
byte b = (byte)(i & 0xFF);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜