Converting int to byte in Android

前端 未结 4 1052
囚心锁ツ
囚心锁ツ 2020-12-21 07:49

Actually I need to transfer the integer value along with the bitmap via bluetooth.. Now my problem is I need to transfer the in

相关标签:
4条回答
  • 2020-12-21 08:06

    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;
    
    0 讨论(0)
  • 2020-12-21 08:14

    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.

    0 讨论(0)
  • 2020-12-21 08:17

    for 0-255 numbers.

    int i = 200; // your int variable
    byte b = (byte)(i & 0xFF);
    
    0 讨论(0)
  • 2020-12-21 08:21

    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);
    }
    
    0 讨论(0)
提交回复
热议问题