简体   繁体   English

如何从八位字节流的十六进制表示形式实例化ArrayBuffer?

[英]How can I instantiate an ArrayBuffer from a hexadecimal representation of an octet stream?

I have binary information coming over a TCP connection (WebSocket). 我有来自TCP连接(WebSocket)的二进制信息。 This is traced to the console in an encoded format like so: 这以编码格式跟踪到控制台,如下所示:

53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 38 37 

I presume this is hex encoding of each of the bytes. 我认为这是每个字节的十六进制编码。

The information is actually protocol buffer information. 该信息实际上是协议缓冲区信息。 I would like to write a function to decode it using a library I have. 我想编写一个函数使用我拥有的库对其进行解码。 The first step is for me to create a buffer object of some kind to encapsulate the binary information for supply to the library. 对我来说,第一步是创建某种缓冲对象,以封装二进制信息以提供给库。

I do not yet know the precise type expectation of the library, but it expects a binary buffer of some sort. 我还不知道该库的确切类型期望,但是它期望某种二进制缓冲区。

The protocol buffer decoding library API looks like so: 协议缓冲区解码库API如下所示:

library.byteBufferToResponse(buffer);

How can I instantiate a "binary buffer" of some kind from a hexadecimal representation of an octet stream? 如何从八位字节流的十六进制表示形式实例化某种“二进制缓冲区”?

var octetStream = '34 36 10 04 1a 05 0a 01 30';
var arrayBuffer = new ArrayBuffer(); // How can I initialize this with the binary data?

ArrayBuffer是类型数组的ArrayBuffer ,因此:

var arrayBuffer = new Uint8Array(octetStream).buffer;

You'll want to use a Typed Array to access the buffer. 您将要使用类型数组来访问缓冲区。 You can directly put that array literal you have into its constructor, it will construct a buffer or the appropriate size. 您可以将您拥有的数组文字直接放入其构造函数中,它将构造一个缓冲区或适当的大小。

like body=53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 38 37 37 38 36 which I interpret as hex encoded bytes. 例如body=53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 38 37 37 38 36 ,我将其解释为十六进制编码的字节。

For that, you can use TypedArray.from with a map function: 为此,可以将TypedArray.from与地图函数配合使用:

var msg = "body=53 54 41 52 54 45 44 3a 31 34 32 38 36 30 32 30 38 37 37 38 36";
var arr = Uint8Array.from(msg.slice(5).split(" "), function(byte) {
    return parseInt(byte, 16);
});
var buffer = arr.buffer; // not sure you actually need this

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

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