Skip to content

Commit bc8dcb8

Browse files
committed
Add fix for big-endian platforms (Closes: #85)
1 parent a458d11 commit bc8dcb8

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

lib/to-buffer.js

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,48 @@
11
var Buffer = require('safe-buffer').Buffer
22

3+
function swapBytes(buf, size) {
4+
var bytes = new Uint8Array(buf);
5+
var len = bytes.length;
6+
var holder;
7+
8+
if (size == 'WORD') {
9+
//16 bit
10+
for (var i = 0; i<len; i+=2) {
11+
holder = bytes[i];
12+
bytes[i] = bytes[i+1];
13+
bytes[i+1] = holder;
14+
}
15+
} else if (size == 'DWORD') {
16+
//32 bit
17+
for (var i = 0; i<len; i+=4) {
18+
holder = bytes[i];
19+
bytes[i] = bytes[i+3];
20+
bytes[i+3] = holder;
21+
holder = bytes[i+1];
22+
bytes[i+1] = bytes[i+2];
23+
bytes[i+2] = holder;
24+
}
25+
}
26+
return bytes;
27+
}
28+
29+
function checkEndian() {
30+
var arrayBuffer = new ArrayBuffer(2);
31+
var uint8Array = new Uint8Array(arrayBuffer);
32+
var uint16array = new Uint16Array(arrayBuffer);
33+
uint8Array[0] = 0xAA; //set first byte
34+
uint8Array[1] = 0xBB; //set second byte
35+
if(uint16array[0] === 0xBBAA) return false;
36+
if(uint16array[0] === 0xAABB) return true;
37+
}
38+
339
module.exports = function (thing, encoding, name) {
440
if (Buffer.isBuffer(thing)) {
541
return thing
642
} else if (typeof thing === 'string') {
743
return Buffer.from(thing, encoding)
844
} else if (ArrayBuffer.isView(thing)) {
9-
return Buffer.from(thing.buffer)
45+
return checkEndian() ? swapBytes(thing.buffer,'DWORD') : Buffer.from(thing.buffer);
1046
} else {
1147
throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
1248
}

0 commit comments

Comments
 (0)