【问题标题】:Java create a checksum in ASCIIJava 在 ASCII 中创建校验和
【发布时间】:2015-09-10 08:49:26
【问题描述】:

我必须将 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

【问题讨论】:

  • Ĥ 不是 ASCII。
  • 对不起,我必须发送一个十六进制
  • 标准 ASCII 字符范围从 0 到 127。

标签: java android bluetooth ascii


【解决方案1】:

已解决:

somma=(char) (somma%128);

【讨论】:

    【解决方案2】:

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

    UTF-8 --> ¤ 000000000000000000000000000000000000c2a4

    UTF-16 --> ¤ 00000000000000000000000000000000feff00a4

    UTF-32 --> ¤ 00000000000000000000000000000000000000a4

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

    【讨论】:

    • 谢谢,我可以处理 String s 以便将某些内容放入 char 中吗?
    • (char)Integer.parseInt(s, 16)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2011-07-18
    • 2021-10-01
    • 2021-04-03
    • 1970-01-01
    • 2013-10-20
    • 2021-12-11
    相关资源
    最近更新 更多