Convert an unsigned byte to a java type

zhaozj2021-02-08  308

. In JAVA, a byte always considered as signed when converted to another type We must mask the sign bit to JAVA, cast to an integer and process the masked bit if needed The following method implements this idea.:

Public class unsignedbyte {

Public static void main (string args []) {

BYTE B1 = 127 // int 127;

BYTE B2 = -128 // int 128;

BYTE B3 = -1 // int 255;

System.out.println (unsignedbyTetoint (B1));

System.out.println (unsignedbyTetoint (b2));

System.out.println (unsignedbyTetoint (B3));

}

Public static int unsignedByTetoint (byte b) {

Return (int) b & 0xff;

}

}

ThereFore for an array of 4 bytes (buf []), Which represents an integer:

INT i = 0;

INT POS = 0;

i = unsignedByToint (buf [pOS ]) << 24;

i = unsignedbyToint (BUF [POS ]) << 16;

i = unsignedbyToint (buf [POS ]) << 8;

i = unsignedbyToint (buf [POS ]) << 0;

NOTE: WHEN Converting BYTE REPRESENTING ANTEGER, IT'S POSSIBLE THAT. SEE DEAL with BIG-Endian and Little-Endian Order

转载请注明原文地址:https://www.9cbs.com/read-844.html

New Post(0)