//convert a byte to int and back
class ConvByteInt {
public static void main(String[] args) {
//signed byte
byte s_byte1 = Byte.parseByte(args[0]);
byte s_byte2 = Byte.parseByte(args[1]);
System.out.println("the bytes are: " + s_byte1 + ", " + s_byte2);
//unsigned ints (logically, -1 EOS)
int u_int1 = s_byte1 >= 0 ? s_byte1 : s_byte1 + 256;
int u_int2 = s_byte2 >= 0 ? s_byte2 : s_byte2 + 256;
System.out.println("the integers are: " + u_int1 + ", " + u_int2);
//convert them back, casts
byte a = (byte) u_int1;
byte b = (byte) u_int2;
System.out.println("the bytes are: " + a + ", " + b);
//convert them back, no casts
//representation 0 - 255 (unsigned ints)
//does NOT check boundary conditions
//are the bit operations even needed ??
byte c = (byte) ((u_int1 & 0x000000FF) <= 127 ? u_int1 : u_int1 - 256);
byte d = (byte) ((u_int2 & 0x000000FF) <= 127 ? u_int2 : u_int2 - 256);
System.out.println("the bytes are: " + c + ", " + d);
}
}
sample out-
17864397:io anujseth$ java ConvByteInt 43 -12
the bytes are: 43, -12
the integers are: 43, 244
the bytes are: 43, -12
the bytes are: 43, -12
No comments:
Post a Comment