简体   繁体   English

将USB键盘数据从字节数组转换为字符串USB4Java

[英]Convert USB keyboard data from byte array to String USB4Java

I am reading a USB Keyboard (QR Code scanner) input using usb4java. 我正在读取使用usb4java的USB键盘(QR码扫描仪)输入。

My code snippet looks like this: 我的代码段如下所示:

byte[] data = new byte[16];
UsbPipe usbPipe = usbEndpoint.getUsbPipe();
if (usbPipe != null) {
    if (!usbPipe.isOpen()) {
        usbPipe.open();
    }
    if (usbPipe.isOpen()) {
        UsbIrp usbIrp = usbPipe.createUsbIrp();
        usbIrp.setData(data);

I have two questions: 我有两个问题:

1] On pressing A, byte array data is 2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0 1]按A时,字节数组数据为2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0
On pressing AB, byte aray data is 2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0,2,0,5,0,0,0,0,0 按下AB键后,字节aray数据为2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0,2,0,5,0,0, 0,0,0

How to convert it into character in java? 如何在Java中将其转换为字符? ie get A or AB after conversion. 即转换后得到A或AB。

2] Currently, I am passing fixed size of byte array in above code snippet. 2]目前,我正在上述代码段中传递字节数组的固定大小。 For example, if I am expecting 1 char, I am passing 16 as size of byte array, for 2 characters 24 as size and so on. 例如,如果我期望1个字符,那么我将传递16作为字节数组的大小,传递2个字符作为24的大小,依此类推。 Is there any other elegant solution for making it dynamic? 还有其他优雅的解决方案可以使其动态吗?

PS: My byte array converter snippet: PS:我的字节数组转换器代码段:

StringBuffer sb = new StringBuffer();
for (byte b : data) {
    sb.append(b);
    sb.append(",");
}
String byteString = sb.toString();
return byteString;

Thanks for any help 谢谢你的帮助

EDIT 1: Full source code here: http://tpcg.io/zt3WfM 编辑1:完整的源代码在这里: http : //tpcg.io/zt3WfM

Based on the documentation the format should be: 根据文档 ,格式应为:

22 00 04 00 00 00 00 00
Offset  Size    Description
0       Byte    Modifier keys status.
1       Byte    Reserved field.
2       Byte    Keypress #1.
3       Byte    Keypress #2.
4       Byte    Keypress #3.
5       Byte    Keypress #4.
6       Byte    Keypress #5.
7       Byte    Keypress #6. 

Based on the ASCII codes 基于ASCII码

// 'A' is 0x65
byte codeA = 0x04;     // The code for A key
cahr a = 0x61 + codeA ;
byte codeX = 0x1B;     // The code for X key
char x = 0x61 + code; // x == 'X'

System.out.println(a);
System.out.println(x);

Or you can use a Map(0x04, 'A') 或者您可以使用Map(0x04,'A')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM