Skip to content

Bit operations

Function: ModifyBit (Setting by bit position)

byte ModifyBit(byte value, byte bit, bool set)

Description:
Modifies a specific bit in a byte value based on its position.

Parameters:
- value: The byte value to be modified.
- bit: Position of the bit to be modified (0-based index).
- set: If true, the specified bit is set to 1; if false, it's set to 0.

Return Value:
Returns the modified byte value.

Usage Example
1
2
3
byte original = 0x05; // 00000101 in binary
byte modified = ModifyBit(original, 2, true);
PrintLine($"Modified byte: {modified}");  // Should output 13 (1101 in binary)

Function: ModifyBit (Setting by mask)

byte ModifyBit(byte value, byte valueToSet, byte mask)

Description:
Sets bits in a byte value using a mask.

Parameters:
- value: The byte value to be modified.
- valueToSet: The byte value that contains bits to be set.
- mask: The mask that indicates which bits in the original byte should be modified.

Return Value:
Returns the modified byte value.

Usage Example
1
2
3
byte original = 0x05; // 00000101 in binary
byte modified = ModifyBit(original, 0x02, 0x02); // Set the 2nd bit to 1
PrintLine($"Modified byte: {modified}");  // Should output 7 (0111 in binary)

Function: ApplyMask

byte ApplyMask(byte value, byte mask)

Description:
Applies a mask to a byte value.

Parameters:
- value: The byte value.
- mask: The mask to be applied.

Return Value:
Returns the byte value after the mask has been applied.

Usage Example
1
2
3
byte original = 0x0F; // 00001111 in binary
byte result = ApplyMask(original, 0x03); // Mask with the two least significant bits
PrintLine($"Resulting byte: {result}");  // Should output 3 (0011 in binary)

Function: TestBit

bool TestBit(byte value, byte bit)

Description:
Tests if a specific bit in a byte value is set.

Parameters:
- value: The byte value.
- bit: Position of the bit to be tested (0-based index).

Return Value:
Returns true if the specified bit is set, otherwise false.

Usage Example
1
2
3
byte original = 0x05; // 00000101 in binary
bool isSet = TestBit(original, 2);
PrintLine($"Is 2nd bit set? {isSet}");  // Should output true