Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

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

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...