This section provides a tutorial example on how to set one bit into a byte array at a specific bit position setBit().
In many applications, information must be stored and operated as bit strings. Unfortunately,
Java does not provide any built-in data types or classes to support bit strings.
There are several third party BitString classes that you can use to store and manage your bit strings.
Another way to store and manage bit strings is to use byte arrays, byte[].
I have used them while implementing DES (Data Encryption Standard) encryption algorithm,
see "Cryptography Tutorials - Herong's Tutorial Notes" at
http://www.herongyang.com/crypto/.
Storing and managing bit strings in byte arrays is not that hard as long as you define a pair of setBit() and getBit()
methods. Here is my set of methods used in my cryptography tutorials. Of course, there is room for improvement in these
methods. Try it yourself.
1. setBit() - To set one bit to a bit string at the specified position with the specified bit value:
The method interface expects the caller to provide the byte array that stores the bit string,
the position in the bit string where bit value needs to be set, and the new bit value given as a "int" value.
The first statement calculates the array index, "posByte", of the affected byte that holds the bit to be set.
The second statement calculates the bit position, "posBit", in the affected byte where the bit value needs to be set.
The third statement fetches the affected byte into a temporary variable, "oldByte".
The fourth statement sets a 0 value to "oldByte" at the bit position of "posBit".
The fifth statement sets the input "val" to "oldByte" at the bit position of "posBit" and assigns to "newByte".
To understand how the fourth statement works, let's assume that posBit = 2. Then the evaluation process of
the statement can be described as: