How to send such complicated hex, binary protocol data accurately using java byte[]?

前端 未结 3 829
猫巷女王i
猫巷女王i 2021-01-14 02:23

I am very confused with this kind of stuffs, What should I send as final command, get always confused 8 bits to 1 byte but how do we make it? Is it only the command packet [

3条回答
  •  情歌与酒
    2021-01-14 02:57

    • In such diagram header block shows mostly like "Bit 7, Bit 6,..,Bit 0" instead of "Bit 0, Bit 1, Bit 2, ... Bit 7", i always wondering why?.

    In typical number writing 0 is the least significant bit 7 the most significant and the byte is written in most significant to least significant 7-0.

    byte  11111111
    place 76543210
    
    • But when i apply in code what is following order for byte st[0] = Bit 7 or Bit 1?

    In your code this is not setting bits this is setting a byte in the byte array

    If you are nervous about setting bits try a class like this:

    public class SimpleByteSetter {
    
      /* b is is byte you are setting
         on is if the bit is set to on or 1
         place is the bit place in the range of 0-7
      */
      public static byte set(final byte b, final boolean on, final int place) {
        if (on) { return (byte) (b | ((1 << place) & 0xFF)); }
        return (byte) (b & (~((1 << place) & 0xFF)));
      }
    
      // 1 == on everything else off (but only use 0!)
      public static byte set(final byte b, final int on, final int place) {
        return set(b, 1==on, place);
      }
    
    }
    

    use it in you code like:

    byte header = 0;
    // get = 0, set = 1, place = 0
    header = SimpleByteSetter(header, 0, 0 ); // get
    // header 2 byte = 0, header 2 byte = 1, place = 1
    header = SimpleByteSetter(header, 0, 1 ); // header 1 byte
    ...
    st[0] = header;
    
    • Also according to this diagram, does it mean every command i send will have Header fixed always

    Yes

    • This is the code i was trying by taking Bit 1 as st[0], Bit 2 as st1 instead of Bit 7 as st[0]. To apply Power off/on test.

    I don't have enough information to actually build the packet but:

    // the header is 1 byte I don't see how to make it two
    // the command is 2 bytes per the table
    // the parameter length is 0 so 1 byte (is there suppose to be a device id?)
    byte[] st = new byte[ 1 + 2 + 1 ];
    
    byte header = 0;
    // get = 0, set = 1, place = 0
    header = SimpleByteSetter(header, 0, 0 ); // get
    // header 2 byte = 0, header 2 byte = 1, place = 1
    header = SimpleByteSetter(header, 0, 1 ); // header 1 byte
    // length 1 byte = 0, length 2 byte = 1
    header = SimpleByteSetter(header, 0, 2 );
    // command 1 byte = 0, command 2 byte = 1; 
    header = SimpleByteSetter(header, 1, 3 );
    
    st[0] = header;
    st[1] = 0x0130 & 0xFF; // poweroff command first byte
    st[2] = 0x0100 & 0xFF; // poweroff second byte
    st[3] = 0;
    

提交回复
热议问题