简体   繁体   English

在Java中将具有偶数奇偶校验字节的UTF-8字符转换为ASCII 7位

[英]converting a UTF-8 character to an ASCII 7 bit with even parity byte in Java

A device I am trying to communicate with takes ASCII 7-bit characters with even parity. 我尝试与之通信的设备采用偶数奇偶校验的ASCII 7位字符。 When trying to convert a UTF-8 character I cast it to an integer then to a binary string. 尝试转换UTF-8字符时,我将其转换为整数,然后转换为二进制字符串。 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. 但是,当使用Byte.parseByte将其转换回时,如果设置了签名位,则会收到NumberFormatError。 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). 因为Byte.parseByte拒绝分析超出字节范围(-128..127)的值,所以您收到错误消息。 So it refuses to parse something like "10001011" which is 139 in decimal. 因此,它拒绝解析类似"10001011"十进制139。 A quick fix could be using Integer.parseInt instead and casting the result to byte: 一种快速修复方法是改用Integer.parseInt并将结果转换为字节:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM