I am receiving and sending a decimal representation of two little endian numbers. I would like to:
- shift one variable 8 bits left
- OR them
- shift a variable number of bits
- create 2 8 bit numbers representing the first and second half of the 16 bit number.
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:
- Let's say that
valis, for example,0xAABB. - Mask
valto get the LSB by&ing with0xFF: result is0xBB. - Shift that result 8 bits to the left: result is
0xBB00. - Shift
val8 bits to the right: result is0xAA(the LSB has "dropped off" the right-hand side). - Mask that result to get the LSB by
&ing with0xFF: result is0xAA. - Combine the results from steps 3 and step 5 by
|ing them together:0xBB00 | 0xAAis0xBBAA.
function swap32(val) {
return ((val & 0xFF) << 24)
| ((val & 0xFF00) << 8)
| ((val >> 8) & 0xFF00)
| ((val >> 24) & 0xFF);
}
Explanation:
- Let's say that
valis, for example,0xAABBCCDD. - Mask
valto get the LSB by&ing with0xFF: result is0xDD. - Shift that result 24 bits to the left: result is
0xDD000000. - Mask
valto get the second byte by&ing with0xFF00: result is0xCC00. - Shift that result 8 bits to the left: result is
0xCC0000. - Shift
val8 bits to the right: result is0xAABBCC(the LSB has "dropped off" the right-hand side). - Mask that result to get the second byte by
&ing with0xFF00: result is0xBB00. - Shift
val24 bits to the right: result is0xAA(everything except the MSB has "dropped off" the right-hand side). - Mask that result to get the LSB by
&ing with0xFF: result is0xAA. - Combine the results from steps 3, 5, 7 and 9 by
|ing them together:0xDD000000 | 0xCC0000 | 0xBB00 | 0xAAis0xDDCCBBAA.
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'
Use the << (bit shift) operator. Ex: 1 << 2 == 4.
I really think that the underlying implementation of JavaScript will use whatever endianess the platform it is running on is using. Since you cannot directly access memory in JavaScript you won't ever have to worry about how numbers are represented physically in memory. Bit shifting integer values always yield the same result no matter the endianess. You only see a difference when looking at individual bytes in memory using pointers.
来源:https://stackoverflow.com/questions/5320439/how-do-i-swap-endian-ness-byte-order-of-a-variable-in-javascript