Converting int to byte in Android

夙愿已清 提交于 2019-12-18 09:06:44

问题


Actually I need to transfer the integer value along with the bitmap via bluetooth.. Now 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)


回答1:


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);
}



回答2:


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;



回答3:


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.




回答4:


for 0-255 numbers.

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


来源:https://stackoverflow.com/questions/5510319/converting-int-to-byte-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!