Java以ASCII格式创建校验和

时间:2015-06-24 08:37:39

标签: java android bluetooth ascii

我必须在字符串中对ASCII求和,并将总和的最后一个字符放在一个字节中,以便在蓝牙上发送字符串。

es: String s = "R002" 
sum: R+0+0+2 = 000000000000000000000000000000000000c3a4 = ä

我尝试发送R(52)+0(30)+0(30)+2(32)+¤(a4)
但是我发送了R(52)+0(30)+0(30)+2(32)+Ä(c3)+¤(a4)

我可以用哪种方式发送¤?

the code:

        String pergolato = "ä";
        String pesto= String.format("%040x", new BigInteger(1, pergolato.substring(0, 1).getBytes(/*YOUR_CHARSET?*/)));

        int zaino = Integer.parseInt(pesto, 16);
        char c = (char) (zaino & 0xff);

        String sum="R002"+c;
        for(int i=0;i<sum.length();i++){
            String s= String.format("%040x", new BigInteger(1, sum.substring(i, i+1).getBytes(/*YOUR_CHARSET?*/)));
            Log.i(TAG, sum.charAt(i)+" "+s);
        }

the LogCat:

R 0000000000000000000000000000000000000052

0 0000000000000000000000000000000000000030

0 0000000000000000000000000000000000000030

2 0000000000000000000000000000000000000032

¤ 000000000000000000000000000000000000c2a4

2 个答案:

答案 0 :(得分:0)

为了我的目的,我修改了一些代码。 不同编码的结果:

UTF-8 - &gt; ¤0000000000000000000000000000000000c2a4

UTF-16 - &gt; ¤000000000000000000000000000000feff00a4

UTF-32 - &gt; ¤000000000000000000000000000000000000a4

import java.math.BigInteger;
import java.nio.charset.Charset;
public class Test2 {
    public static void main(String[] args) {
        String pergolato = "ä";
        String pesto= String.format("%040x", new BigInteger(1, pergolato.getBytes()));

        int zaino = Integer.parseInt(pesto, 16);
        char c = (char) (zaino & 0xff);

        String sum="R002"+c;
        for(int i=0;i<sum.length();i++){
            String s= String.format("%040x", new BigInteger(1, sum.substring(i, i+1).getBytes(Charset.forName("UTF-32"))));
            System.out.println(sum.charAt(i)+" "+s);
        }
    }

}

答案 1 :(得分:0)

解决:

somma=(char) (somma%128);