How to Convert Int to Unsigned Byte and Back

前端 未结 10 655
死守一世寂寞
死守一世寂寞 2020-11-28 23:04

I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.

I also need to convert that byte ba

10条回答
  •  Happy的楠姐
    2020-11-28 23:29

    The solution works fine (thanks!), but if you want to avoid casting and leave the low level work to the JDK, you can use a DataOutputStream to write your int's and a DataInputStream to read them back in. They are automatically treated as unsigned bytes then:

    For converting int's to binary bytes;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    int val = 250;
    dos.write(byteVal);
    ...
    dos.flush();
    

    Reading them back in:

    // important to use a (non-Unicode!) encoding like US_ASCII or ISO-8859-1,
    // i.e., one that uses one byte per character
    ByteArrayInputStream bis = new ByteArrayInputStream(
       bos.toString("ISO-8859-1").getBytes("ISO-8859-1"));
    DataInputStream dis = new DataInputStream(bis);
    int byteVal = dis.readUnsignedByte();
    

    Esp. useful for handling binary data formats (e.g. flat message formats, etc.)

提交回复
热议问题