Skip to content

Commit 8399c9a

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

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

lib/to-buffer.js

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

3+
function swapBytes(buf, size) {
4+
var bytes = new Uint8Array(buf.slice());
5+
var len = bytes.length;
6+
var holder;
7+
8+
if (size == 2) {
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 == 4) {
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+
} else if (size == 8) {
26+
//32 bit
27+
for (var i = 0; i<len; i+=8) {
28+
holder = bytes[i];
29+
bytes[i] = bytes[i+7];
30+
bytes[i+7] = holder;
31+
holder = bytes[i+1];
32+
bytes[i+1] = bytes[i+6];
33+
bytes[i+6] = holder;
34+
holder = bytes[i+2];
35+
bytes[i+2] = bytes[i+5];
36+
bytes[i+5] = holder;
37+
holder = bytes[i+3];
38+
bytes[i+3] = bytes[i+4];
39+
bytes[i+4] = holder;
40+
}
41+
}
42+
return Buffer.from(bytes);
43+
}
44+
45+
function checkEndian() {
46+
var arrayBuffer = new ArrayBuffer(2);
47+
var uint8Array = new Uint8Array(arrayBuffer);
48+
var uint16array = new Uint16Array(arrayBuffer);
49+
uint8Array[0] = 0xAA; //set first byte
50+
uint8Array[1] = 0xBB; //set second byte
51+
if(uint16array[0] === 0xBBAA) return false;
52+
if(uint16array[0] === 0xAABB) return true;
53+
}
54+
355
module.exports = function (thing, encoding, name) {
456
if (Buffer.isBuffer(thing)) {
557
return thing
658
} else if (typeof thing === 'string') {
759
return Buffer.from(thing, encoding)
860
} else if (ArrayBuffer.isView(thing)) {
9-
return Buffer.from(thing.buffer)
61+
return checkEndian() ? swapBytes(thing.buffer,thing.BYTES_PER_ELEMENT) : Buffer.from(thing.buffer);
1062
} else {
1163
throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
1264
}

0 commit comments

Comments
 (0)