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)
Bit order usually follows the same endianness as the byte order for a given computer system. That is, in a big endian system the most significant bit is stored at the lowest bit address; in a little endian system, the least significant bit is stored at the lowest bit address.
In little-endian style, the bytes are written from left to right in increasing significance. In big-endian style, the bytes are written from left to right in decreasing significance. The swapbytes function swaps the byte ordering in memory, converting little endian to big endian (and vice versa).
Endianness only affects the order of bytes (not bits) in a data word. Since a char is always one-byte in size, you don't have to do any adjustments to them. The standard library function ntohl changes the byte order of an unsigned integer ( l ) from network byte order ( n ) to host byte order ( h ).
Endian and endianness (or "byte-order") describe how computers organize the bytes that make up numbers. Each memory storage location has an index or address. Every byte can store an 8-bit number (i.e. between 0x00 and 0xff ), so you must reserve more than one byte to store a larger number.
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
.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