I am receiving and sending a decimal representation of two little endian numbers. I would like to:
javascript (according to https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators) uses big endian representation when shifting...
endianness is a bit foreign to me (I am only 90 percent sure that my outlined steps are what i want.) so swapping is a bit dizzying. please help! I only really need to know how to swap the order in an efficient manner. (I can only think of using a for loop on a toString() return value)
function swap16(val) {
return ((val & 0xFF) << 8)
| ((val >> 8) & 0xFF);
}
Explanation:
val is, for example, 0xAABB.val to get the LSB by &ing with 0xFF: result is 0xBB.0xBB00.val 8 bits to the right: result is 0xAA (the LSB has "dropped off" the right-hand side).&ing with 0xFF: result is 0xAA.|ing them together:0xBB00 | 0xAA is 0xBBAA.function swap32(val) {
return ((val & 0xFF) << 24)
| ((val & 0xFF00) << 8)
| ((val >> 8) & 0xFF00)
| ((val >> 24) & 0xFF);
}
Explanation:
val is, for example, 0xAABBCCDD.val to get the LSB by &ing with 0xFF: result is 0xDD.0xDD000000.val to get the second byte by &ing with 0xFF00: result is 0xCC00.0xCC0000.val 8 bits to the right: result is 0xAABBCC (the LSB has "dropped off" the right-hand side).&ing with 0xFF00: result is 0xBB00.val 24 bits to the right: result is 0xAA (everything except the MSB has "dropped off" the right-hand side).&ing with 0xFF: result is 0xAA.|ing them together:0xDD000000 | 0xCC0000 | 0xBB00 | 0xAA is 0xDDCCBBAA.Such function can be used to change endianness in js:
const changeEndianness = (string) => {
const result = [];
let len = string.length - 2;
while (len >= 0) {
result.push(string.substr(len, 2));
len -= 2;
}
return result.join('');
}
changeEndianness('AA00FF1234'); /// '3412FF00AA'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With