Search code examples
javaparsingconverters8-bit

Java - Parser Library to parse a decimal to byte in x-bits


I have a problem with parsers.

The problem is I get an integer such as "8" and I need to transform this to an 8-bit unsigned byte. Later on I will receive an integer "56" and need to transform it using the the same method but when I get a "-53" (for example) I shall say that was a mistake in the communication and sending.

For example,

number = 538; //or 63492873 or 8 or 17826312631 or -231 or whatever
try{
  byte response[] = Parse8BitUnsigned(number);
}catch(Idkexcepcion ex){
  System.out.println("the number is a signed one");
  byte response[] = Parse8BitSigned(number);
}

Note: Parse8BitSigned() and Parse8BitSigned() had not been implemented. I need that method for any number


Solution

  • You can use ByteBuffer to do what you want:

    String number="8";
    int num = Integer.valueOf(number);
    if(num < 0 ) //ERROR
    // Return 8 in a 4 bytes array
    byte[] bytes = ByteBuffer.allocate(4).putInt(num).array();