在保留字节的同时在JavaScript中连接十六进制字节和字符串

时间:2014-02-13 18:31:36

标签: javascript utf-8 hex concatenation

我想使用JavaScript连接十六进制值和字符串。

var hexValue = 0x89;
var png = "PNG";

字符串“PNG”相当于0x500x4E0x47的串联。

通过

连接hexValuepng
var concatHex = String.fromCharCode(0x89) + String.fromCharCode(0x50) 
              + String.fromCharCode(0x4E) + String.fromCharCode(0x47);

...给出一个字节数为5的结果,因为第一个十六进制值需要一个控制字符:

C2 89 50 4E 47

我正在使用原始图像数据,我有hexValuepng,并且需要连接它们而不包含此控制字符。

  1. 有没有办法修剪控制角色?
  2. 鉴于我有一个字节数组,是否有更好的方法将它们连接起来并保留字符串?

1 个答案:

答案 0 :(得分:0)

我正在调查,我发现在javascript中实现这种有效的JavaScript类型数组被使用。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

http://msdn.microsoft.com/en-us/library/br212485(v=vs.94).aspx

在这里,我编写了一个代码(未经过测试)来执行您想要的任务:

var png = "PNG";
var hexValue = 0x89;
var lenInBytes = (png.Length + 1) * 8; //left an extra space to concat hexValue

var buffer = new ArrayBuffer(lenInBytes); //create chunk of memory whose bytes are all pre-initialized to 0
var int8View = new Int8Array(buffer); //treat this memory like int8

for(int i = 0; i < png.Length ; i++)
    int8View[i] = png[i]  //here convert the png[i] to bytes

//at this point we have the string png as array of bytes

    int8View[png.Length] = hexValue //here the concatenation is performed

希望它有所帮助。

相关问题