【问题标题】:Combine multiple uint8 and uint16 into 1 byte array将多个 uint8 和 uint16 组合成 1 字节数组
【发布时间】:2014-08-28 12:59:22
【问题描述】:

我对 Java 编程相当陌生,我正在尝试为 Android (4.3+) 开发一款低功耗蓝牙 (4.0) 健身设备。我从不同的硬件制造商那里购买了一堆不同的设备进行测试,其中一个向设备发送值的说明如下:

Characteristic Fitness Goals
size: 8 bytes    
D0 D1 D2 D3 D4 D5 D6 D7

D0: number of days in month, uint8_t   
D1 D2: distance walked , uint16_t
D3 D4: distance ran, uint16_t
D5 D6: steps taken, uint16_t
D7: number of users, uint8_t

问题来了:

我需要将 5 个 int 值放入将写入设备的字节数组中。 以这些值为例:

16 (# days in month)
450 (distance walked)
334 (distance ran)
800 (steps taken)
4 (number of users)

我不确定如何获取这些不同的 uint8_t 和 uint16_t 值并将它们放入一个字节数组中以便写入蓝牙设备。谁能告诉我这是怎么做到的?

谢谢!

【问题讨论】:

    标签: java android bluetooth


    【解决方案1】:

    您可以使用ByteBuffer,如下所示:

    ByteBuffer buf = ByteBuffer.allocate(8);
    
    // Depending on the device you may need to include the following line
    // buf.order(ByteOrder.LITTLE_ENDIAN);
    
    buf.put((byte)16); // (# days in month)
    buf.putShort(450); // (distance walked)
    buf.putShort(334); // (distance ran)
    buf.putShort(800); // (steps taken)
    buf.put((byte)4);  // (number of users)
    
    byte[] byteArray = buf.array();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多