Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS Big-Endian UCS-2

I'm working with Node.JS. Node's buffers support little-endian UCS-2, but not big-endian, which I need. How would I do so?

like image 979
skeggse Avatar asked Sep 18 '11 03:09

skeggse


1 Answers

According to wikipedia, UCS-2 should always be big-endian so it's odd that node only supports little endian. You might consider filing a bug. That said, switching endian-ness is fairly straight-forward since it's just a matter of byte order. So just swap bytes around to go back and forth between little and big endian, like so:

function swapBytes(buffer) {
  var l = buffer.length;
  if (l & 0x01) {
    throw new Error('Buffer length must be even');
  }
  for (var i = 0; i < l; i += 2) {
    var a = buffer[i];
    buffer[i] = buffer[i+1];
    buffer[i+1] = a;
  }
  return buffer; 
}
like image 148
broofa Avatar answered Sep 25 '22 19:09

broofa