rochars /
endianness
| 1 | /*! |
||
| 2 | * endianness |
||
| 3 | * Swap endianness in byte arrays. |
||
| 4 | * Copyright (c) 2017 Rafael da Silva Rocha. |
||
| 5 | * https://github.com/rochars/endianness |
||
| 6 | * |
||
| 7 | */ |
||
| 8 | |||
| 9 | /** |
||
| 10 | * Swap the endianness of units of information in a byte array. |
||
| 11 | * The original array is modified in-place. |
||
| 12 | * @param {!Array<number>|!Array<string>|Uint8Array} bytes The bytes. |
||
| 13 | * @param {number} offset The number of bytes of each unit of information. |
||
| 14 | */ |
||
| 15 | function endianness(bytes, offset) { |
||
| 16 | let len = bytes.length; |
||
| 17 | let i = 0; |
||
| 18 | while (i < len) { |
||
| 19 | swap(bytes, offset, i); |
||
| 20 | i += offset; |
||
| 21 | } |
||
| 22 | } |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Swap the endianness of a unit of information in a byte array. |
||
| 26 | * The original array is modified in-place. |
||
| 27 | * @param {!Array<number>|!Array<string>|Uint8Array} bytes The bytes. |
||
| 28 | * @param {number} offset The number of bytes of the unit of information. |
||
| 29 | * @param {number} index The start index of the unit of information. |
||
| 30 | */ |
||
| 31 | function swap(bytes, offset, index) { |
||
| 32 | let x = 0; |
||
| 33 | let y = offset - 1; |
||
| 34 | let limit = parseInt(offset / 2, 10); |
||
| 35 | let swap; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 36 | while(x < limit) { |
||
| 37 | swap = bytes[index + x]; |
||
|
0 ignored issues
–
show
|
|||
| 38 | bytes[index + x] = bytes[index + y]; |
||
| 39 | bytes[index + y] = swap; |
||
| 40 | x++; |
||
| 41 | y--; |
||
| 42 | } |
||
| 43 | } |
||
| 44 | |||
| 45 | module.exports = endianness; |
||
| 46 |