How do I swap endian-ness (byte order) of a variable in javascript

griotspeak picture griotspeak · Mar 16, 2011 · Viewed 24.4k times · Source

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)

Answer

LukeH picture LukeH · Mar 16, 2011
function swap16(val) {
    return ((val & 0xFF) << 8)
           | ((val >> 8) & 0xFF);
}

Explanation:

  1. Let's say that val is, for example, 0xAABB.
  2. Mask val to get the LSB by &ing with 0xFF: result is 0xBB.
  3. Shift that result 8 bits to the left: result is 0xBB00.
  4. Shift val 8 bits to the right: result is 0xAA (the LSB has "dropped off" the right-hand side).
  5. Mask that result to get the LSB by &ing with 0xFF: result is 0xAA.
  6. Combine the results from steps 3 and step 5 by |ing them together:
    0xBB00 | 0xAA is 0xBBAA.

function swap32(val) {
    return ((val & 0xFF) << 24)
           | ((val & 0xFF00) << 8)
           | ((val >> 8) & 0xFF00)
           | ((val >> 24) & 0xFF);
}

Explanation:

  1. Let's say that val is, for example, 0xAABBCCDD.
  2. Mask val to get the LSB by &ing with 0xFF: result is 0xDD.
  3. Shift that result 24 bits to the left: result is 0xDD000000.
  4. Mask val to get the second byte by &ing with 0xFF00: result is 0xCC00.
  5. Shift that result 8 bits to the left: result is 0xCC0000.
  6. Shift val 8 bits to the right: result is 0xAABBCC (the LSB has "dropped off" the right-hand side).
  7. Mask that result to get the second byte by &ing with 0xFF00: result is 0xBB00.
  8. Shift val 24 bits to the right: result is 0xAA (everything except the MSB has "dropped off" the right-hand side).
  9. Mask that result to get the LSB by &ing with 0xFF: result is 0xAA.
  10. Combine the results from steps 3, 5, 7 and 9 by |ing them together:
    0xDD000000 | 0xCC0000 | 0xBB00 | 0xAA is 0xDDCCBBAA.