Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Flip the most significant bit in a byte
Message
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Versions des environnements
Environment:
C# 2.0
Divers
Thread ID:
01158678
Message ID:
01158742
Vues:
26
This message has been marked as the solution to the initial question of the thread.
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.
-----
Fabio Vazquez
http://www.fabiovazquez.com
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform