【问题标题】:send tdata frame to a socket将 tdata 帧发送到套接字
【发布时间】:2016-06-14 14:09:09
【问题描述】:

字节[] 要求=新字节[2]; 假设 demande 是一个数据帧,它将被发送到一个套接字。 如果我想发送 200,应该是 byte[0] 和 byte[1]。我尝试写 byte[0]=1 和 byte[1]=-56 ( 1*256 - 56)=200 但它没有工作。我该怎么办?

【问题讨论】:

    标签: java android byte frame


    【解决方案1】:

    我假设数字 200 是十进制值。 由于 200 小于 255,它将适合一个字节,因为 200 的十六进制值是 0xC8。

    所以在您的情况下,您有两个选择。哪个是正确的取决于您使用的协议。

    要么

    byte[] demande = { 0x00, 0xC8 };  // little endian
    

    byte[] demande = { 0xC8, 0x00 };  // big endian
    

    或者如果你喜欢

    byte[] demande = new byte[2];
    demande[0] = 0x00;
    demande[1] = 0xC8;
    

    (小端)

    【讨论】:

    • 0xC8 不被接受,最大 0x80 被接受,因为我认为它是一个有符号字节 -128 到 128
    • @pape 如果不阅读与您通信的设备的协议,就很难给出更好的建议。您可以尝试发送三个字节,例如 byte[] demande = { '2', '0', '0' };如果是 ASCII 协议。
    【解决方案2】:

    您可以使用ByteBuffer 类来创建一个字节数组。如果要将整数 200 转换为字节数组:

    ByteBuffer b = ByteBuffer.allocate(2);
    b.putInt(0x000000c8);
    
    byte[] result = b.array();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      相关资源
      最近更新 更多