Need help with Big Endian to Little Endian swap in C#

Mr_Fulano
Mr_Fulano used Ask the Experts™
on
Hi, I'm working with a Byte Array and have come across some bytes that are in Big Endian. I need to convert them to Little Endian. I've done a lot of searching on the Internet, but there doesn't seem to be a real consensus on which approach is best. I was hoping for something simple and elegant.

Lets use this as an example of what I need to do.... I have byte 0x00400000 and its in Big Endian. I need to end up with 0x00004000, which is the Little Endian syntax.

The result has to remain in Hex, or at least a Sting, but we can drop the 0x part of it... I just need the bits to be in the right order.

Does anyone have a nice simple approach for this?

Thank you for your help,
Fulano
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
If you're dealing with the byte array, then just swap the order. Let's say that you have a 4-byte number at the very beginning of the array:

var data = new byte[] { 0, 64, 0, 0 };

// Reverse 4 bytes
var tmp = data[0]; 
data[0] = data[3];
data[3] = tmp;
tmp = data[1];
data[1] = data[2];
data[2] = tmp;

Open in new window


This probably doesn't need saying but make sure you are parsing the data correctly first. You have to individually reverse the numbers based on their type (short, long, etc).
Architect - Coder - Mentor
Commented:
Hi,
I assume that you know which bytes from the array should be rotated.
You can take that specific byte and apply bit masking and bitwise operations as follows:

byte valueToRotate = yourByteArray[index];
byte msb = valueToRotate & 0x11110000 >> 4;
byte lsb = valueToRotate & 0x00001111 << 4;
byte rotatedValue = lsb l msb;

Author

Commented:
Thank you both. I actually ended up coming up with my own solution, but both your comments were useful to help me get to where I needed to get. I appreciate your help. I have spit the point equally (at least I think I have).... the new way of awarding points is so much worse than the older FAR more simple approach.

Thanks again.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial