A device I am trying to communicate with takes ASCII 7-bit characters with even parity. When trying to convert a UTF-8 character I cast it to an integer then to a binary string. check the string and then set the parity bit if needed.
However when converting it back using Byte.parseByte I get a NumberFormatError if the signed bit is set. How can I get round this?
public byte addParity(byte b){
int a = (int)b;
int c = 0;
String s = Integer.toBinaryString(a);
for(int i=0; i!=(8-s.length());)
{
s = "0" +s;
}
for(int i=0; i<s.length(); i++){
if(s.substring(i, i+1).equals("1"))c++;
}
if(c%2==0)return b;
else return Byte.parseByte(("1"+s.substring(1)),2);
}
You are getting the error because Byte.parseByte
refuses to parse values out of the range of byte (-128..127). So it refuses to parse something like "10001011"
which is 139 in decimal. A quick fix could be using Integer.parseInt
instead and casting the result to byte:
else return (byte) Integer.parseInt(("1"+s.substring(1)),2);
I'd however step back and redo the whole thing with bitwise arithmetic.
要设置一点,它应该足以执行以下操作:
return (byte) (b | 0x80);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.