Byte Flipper - Code Segment

4

1

Posted

Introduction: Byte Flipper - Code Segment

If you ever find yourself needing to flip a byte to preserve Endianness, try this quick little implementation!

byte byteFlipper(byte inByte) // Flip a Byte!
{
    flippedByte = 0;
    workingByte = 0;
    for (int i = 0; i <= 7; i++)
    {
        workingByte = bitRead(inByte, i);
	flippedByte |= workingByte << (7 - i);
    }
    return flippedByte; 
}

Algorithm:

- Pass in a byte

- Read bit starting with the i-th

- Store in i-th place of workingByte variable

- Shift that bit left by i places

- Take bitwise logical OR with workingByte and flippedByte

eg.

flippedByte = 00000000
workingByte = 00000001
	OR ____________
flippedByte = 00000001       

- Repeat 8 times

- Return flipped byte

Note: This code can be changed to accommodate any size data type.

Share

    Recommendations

    • Science of Cooking

      Science of Cooking
    • Pocket-Sized Contest

      Pocket-Sized Contest
    • Spotless Contest

      Spotless Contest
    user

    We have a be nice policy.
    Please be positive and constructive.

    Tips

    Questions

    Comments

    Hello there! We're glad you want to share something with the
    Instructables community! And we’re here to help you out. Due to some recent
    changes on the site, we are no longer able to publish stand-alone videos and
    other forms of incomplete posts. In order to be published live on the site,
    Instructables must consist of the following things:

    - Multiple steps
    showing how you made your project

    - Written
    instructions in each step

    - Your own original
    images

    Beyond making your Instructable simply publishable, this
    guide (https://www.instructables.com/id/How-to-Create-a-Feature-Worthy-Instructable/)
    explains what is required to have your Instructables featured by our site
    editors. It’s very helpful, and definitely worth checking out. We would love to
    review your project again after you have made the necessary edits, and we will
    publish your project if it is eligible. If you have any questions, please feel
    free to ask right here or send us an email at service@instructables.com.

    Best,

    Community Manager