简体   繁体   中英

Convert Byte array to Binary in JavaScript

I have a TypedArray of bytes in JavaScript, and I need to convert this into binary, in order to send to a USB device in a Chrome extension using chrome.usb.controlTransfer .

Simplified Example:

var message = new Uint8Array(3);
message[0] = 1;
message[1] = 2;
message[3] = 3;

var transferInfo = {
    direction: 'out',
    recipient: 'device',
    requestType: 'standard',
    request: 0,
    value: 0,
    index: 0,
    data: message
};

// 'device' is a valid handle to a device found with chrome.usb.findDevices
chrome.usb.controlTransfer(device, transferInfo, function(r) { console.log(r); });

This gives me the error:

Uncaught Error: Invalid value for argument 2. Property 'data': Expected 'binary' but got 'object'.

I'm not sure how to get from Uint8Array to whatever is considered to be 'binary' in JavaScript. It's possible this is something chrome-specific, but I can't find any examples of calling this function in this way either.

I've seen the Mozilla Documentation , but this appears to be specific to sending data via XMLHttpRequest.

It seems I missed the example within the Chrome documentation .

var message = new Uint8Array(3);
message[0] = 1;
message[1] = 2;
message[3] = 3;

var binaryMessage = message.buffer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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