Concatenating hex bytes and strings in JavaScript

2019-07-28 17:46发布

问题:

I would like to concatenate a hex value and a string using JavaScript.

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

The string "PNG" is equivalent to the concatenation of 0x50, 0x4E, and 0x47.

Concatenating hexValue and png via

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

...give a result with a byte count of 5 because of the first hex value needing a control character:

C2 89 50 4E 47

I am working with raw image data where I have hexValue and png and need to concatenate them without this control character being included.

  1. Is there a way to trim off the control character?
  2. Given I have an array of bytes, is there a better way to concatenate them and a string while preserving the bytes?

回答1:

Well i was investigating and i found that in javascript to achieve this eficienly JavaScript typed arrays is used.

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

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

Here i wrote a code (not tested) to perform what you want:

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

Well hope it helps.