Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Flip the most significant bit in a byte
Message
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
C# 2.0
Miscellaneous
Thread ID:
01158678
Message ID:
01158839
Views:
20
Fabio,
Thank you for a very elegant solution. Stars have been issued.

Thanks,
Einar

>Hi Einar,
>
>A commonly used technique to toggle a bit into a byte is to XOR the original byte with a bit mask that has the position you want to flip set to 1. The rest of bits must be set to 0. Let't see an example of this arithmetic:
>
>Take 1 (0000001) as your original number. Now, assuming that you want to toggle the bit 7, your bit mask will be 10000000 (bit 7 on and the others off). This is the result:
>
>
>00000001 (1)
>XOR
>10000000 (128) <- this is always the bit mask to toggle the bit 7
>--------
>10000001 (129)
>
>
>So, the code to make this work is something like this:
>
>
>private byte FlipBit7(byte oldByte)
>{
>    byte bitMaskToFlipBit7 = 128;    // 10000000
>    return oldByte ^= bitMaskToFlipBit7;
>}
>
>
>HTH.
Semper ubi sub ubi.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform