【问题标题】:Concatenating hex bytes and strings in JavaScript while preserving bytes在 JavaScript 中连接十六进制字节和字符串,同时保留字节
【发布时间】:2014-03-12 19:48:13
【问题描述】:

我想使用 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. 鉴于我有一个字节数组,有没有更好的方法来连接它们和一个字符串,同时保留字节?

【问题讨论】:

  • 我知道这听起来很奇怪,但是寻找一个在 Firefox 3 中使用二进制 ajax 的旧示例,你会找到你需要的循环代码......
  • @dandavis,你有那个链接吗?我已经将我的十六进制和字符串作为变量。
  • @Mat 你的字符串是 utf8 编码的吧?
  • @emcas88,是的。可以假设。
  • 我说的是 binChar = char % 255 的循环体

标签: javascript utf-8 hex concatenation


【解决方案1】:

嗯,我正在调查,我发现在 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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2014-05-26
    • 2015-01-17
    • 2013-05-29
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2013-08-09
    • 2012-09-25
    相关资源
    最近更新 更多