I am using java's built in Integer.toBinaryString(myInt) to convert to a binary string and then I am converting that 32-bit string into an 8-bit string.
My issue lies in that when converting the number back into a signed-integer I lose the sign.
Example:
My Int = -5.
Binary representation = 11111011.
Converting back to integer: 251.
Some of my code:
//Converts an integer to 8-bit binary.
public static String convertTo8BitBinary(int myNum){
String intToConv = Integer.toBinaryString(myNum);
//the number is less than 8-bits
if(intToConv.length()<8){
String append="";
for(int i = 8 - intToConv.length(); i>0;i--){
append += "0";
}
intToConv = append+intToConv;
//the number is more than 8 bits
}else {
intToConv = intToConv.substring(intToConv.length() - 8, intToConv.length());
}
return intToConv;
}
//Converts an 8-bit binary string to an integer.
public static int convertToIntegerFromBinary(String b){
return Integer.parseInt(b,2);
}
Any ideas how I can retain the sign? Does the Integer.parseInt(b,2) not work for signed integers? Is there a radix that does work for signed binary?