C# Integer Increment Binary: Bits

This C# article shows bits change as an integer is incremented. It displays bits as 1 and 0.

Bits change as an integer is incremented.

Binary arithmetic uses a specific pattern for incrementing an integer. This can be demonstrated in a program using the C# language. This gives us a better idea of how computers work.

Increment IntDecrement Int


Example. This program text in the C# language demonstrates how the bits in an integer are changed as the number is incremented. In other words, it shows you the bits for the value 0, then the bits for the value 1, then for value 2.


And: By looking at the output, we see how the bits in the integer are modified at each successive integral value.

C# program that displays bits, increments integer

using System;

class Program
    static void Main()
	// Increment the counter infinitely.
	// ... Display the bits each time.
	int i = 0;
	while (true)
	    Console.WriteLine("{0} = {1}",
		GetIntBinaryString(i), i);

    static string GetIntBinaryString(int n)
	// Use method body from:
	// ... binary-representation


00000000000000000000000000000000 = 0
00000000000000000000000000000001 = 1
00000000000000000000000000000010 = 2
00000000000000000000000000000011 = 3
00000000000000000000000000000100 = 4
00000000000000000000000000000101 = 5
00000000000000000000000000000110 = 6
00000000000000000000000000000111 = 7
00000000000000000000000000001000 = 8
00000000000000000000000000001001 = 9

The Main entry point takes an int type and increments it in an infinite loop. At each iteration, it displays the binary representation (bits) of the integer and also the decimal form.

Tip: The GetIntBinaryString method is available on this site. You can simply paste in the method body to complete the program.

If we study the output of the program, we see a pattern of how bits are changed to increment a number. The first zero (0) bit to the right of the binary representation is changed to a one (1).

Then: All bits that are one (1) are changed to zero (0) to the right of the bit that was changed.



Discussion. This article was inspired by the book Hacker's Delight by Henry S. Warren. The book described Gray Code. This code is a way of representing integers such that each successive integer (such as 1, 2, 3) is different by only one bit.


And: In our program, successive integers are different by more than one bit when incrementing to 4, 6 and 8.

Hacker's Delight: hackersdelight.org

Note: The book Hacker's Delight isn't about security breaches or food but focuses on binary arithmetic.


Summary. We evaluated the binary representation of the integer type as it is incremented. We saw how the bits are modified. Seeing this process helps us conceptualize the binary codes in the computer memory in many programs.