The Direct Answer: What is the Binary Code for 4?

The binary code for the decimal number 4 is 100 (or 0100 in a standard 4-bit embedded system). In digital logic, this means the third bit (Bit 2, counting from zero) is HIGH (1), representing $2^2 = 4$, while Bits 0, 1, and 3 are LOW (0). If you are configuring a microcontroller GPIO register or writing C++ code, setting Bit 2 to 1 outputs the binary code for 4.

Understanding this isn't just academic trivia; it is the foundation of bitmasking, memory optimization, and hardware control. When you read a 4-channel DIP switch or send a command to a motor driver, you are manipulating these exact bit positions. For a deeper dive into base-2 mathematics, the All About Circuits digital textbook provides an excellent breakdown of binary counting sequences.

Project Build: 4-Bit Binary Indicator & Match Detector

Difficulty: Beginner-Intermediate | Time: 45 minutes

To see the binary code for 4 in action, we will build a 4-bit binary counter using an ESP32. The system will cycle through numbers 0 to 15, displaying the state on four LEDs and an I2C OLED screen. When the counter hits exactly 4 (binary 0100), a specific match condition will trigger, highlighting how microcontrollers evaluate bitwise states.

Parts List

  • Microcontroller: ESP32 DevKit V1 (30-pin, ESP32-WROOM-32 module)
  • Display: 0.96-inch I2C OLED (SSD1306 driver, 128x64 resolution)
  • Indicators: 4x 5mm Red LEDs
  • Current Limiting: 4x 220Ω through-hole resistors (1/4W)
  • Input: 1x 6x6mm tactile pushbutton
  • Hardware: Half-size breadboard, male-to-female and male-to-male jumper wires

Pin Mapping Table

ComponentFunctionESP32 GPIONotes
LED 0Bit 0 (1s place)GPIO 25LOW = 0, HIGH = 1
LED 1Bit 1 (2s place)GPIO 26LOW = 0, HIGH = 2
LED 2Bit 2 (4s place)GPIO 27This pin represents the '4' bit
LED 3Bit 3 (8s place)GPIO 14LOW = 0, HIGH = 8
PushbuttonCycle CounterGPIO 32Internal pull-up enabled
OLED SDAI2C DataGPIO 21Default ESP32 I2C SDA
OLED SCLI2C ClockGPIO 22Default ESP32 I2C SCL
Bench Tip: Notice we intentionally avoided GPIO 12 and GPIO 15 for our LEDs. GPIO 12 is a strapping pin for flash voltage selection on the ESP32-WROOM-32; pulling it HIGH at boot can cause the module to hang or brick the boot sequence. Always consult the Espressif ESP32 Datasheet for strapping pin constraints before wiring.

Wiring Steps & C++ Implementation

Wiring Steps

  1. Place the ESP32 on the breadboard, ensuring it straddles the center trench so all pins are accessible.
  2. Wire the LEDs: Connect the anode (long leg) of each LED to its respective GPIO (25, 26, 27, 14) through a 220Ω resistor. Connect all cathodes (short leg) to the common ground rail.
  3. Wire the Button: Connect one leg of the tactile button to GPIO 32 and the other to ground. We will use the ESP32's internal pull-up resistor in code.
  4. Wire the OLED: Connect VCC to 3.3V, GND to ground, SDA to GPIO 21, and SCL to GPIO 22.
  5. Verify Power: Ensure your USB cable is data-capable and plug it into your PC. The ESP32 onboard blue LED (GPIO 2) should flash briefly on boot.

Complete Compilable Code

This code targets the ESP32 DevKit V1 board variant in the Arduino IDE (using the official Espressif ESP32 core). It requires the Adafruit_SSD1306 and Adafruit_GFX libraries installed via the Library Manager.

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// --- Pin Definitions ---
#define LED_BIT0 25
#define LED_BIT1 26
#define LED_BIT2 27 // The '4' bit
#define LED_BIT3 14
#define BTN_PIN  32

// --- Display Definitions ---
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   -1
#define SCREEN_ADDRESS 0x3C

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const int ledPins[] = {LED_BIT0, LED_BIT1, LED_BIT2, LED_BIT3};
int counter = 0;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

void setup() {
  Serial.begin(115200);
  
  // Initialize GPIOs
  for(int i=0; i<4; i++) {
    pinMode(ledPins[i], OUTPUT);
    digitalWrite(ledPins[i], LOW);
  }
  pinMode(BTN_PIN, INPUT_PULLUP);

  // Initialize I2C Display with Error Handling
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed or I2C timeout"));
    // Halt execution to prevent undefined behavior
    while(true) { 
      digitalWrite(LED_BIT2, HIGH); // Flash the '4' LED as a hardware error code
      delay(200);
      digitalWrite(LED_BIT2, LOW);
      delay(200);
    }
  }
  
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.display();
}

void loop() {
  int reading = digitalRead(BTN_PIN);

  // Debounce logic
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading == LOW) { // Button pressed (pulled to ground)
      counter++;
      if (counter > 15) counter = 0; // 4-bit max is 15
      updateOutputs();
    }
  }
  lastButtonState = reading;
}

void updateOutputs() {
  // Write binary state to LEDs using bitwise AND
  for(int i=0; i<4; i++) {
    digitalWrite(ledPins[i], (counter >> i) & 1);
  }

  // Update OLED
  display.clearDisplay();
  display.setCursor(0, 0);
  display.setTextSize(2);
  display.print("Dec: ");
  display.println(counter);
  
  display.setTextSize(1);
  display.print("Bin: ");
  for(int i=3; i>=0; i--) {
    display.print((counter >> i) & 1);
  }
  display.println();

  // Match Detector: Is the binary code exactly 4? (0100)
  if (counter == 4) {
    display.setTextSize(2);
    display.setCursor(0, 40);
    display.println("MATCH: 4!");
  }
  display.display();
}

Debugging: When the Binary Output Fails

When working with I2C peripherals and bitwise operations on the ESP32, things can fail silently or throw cryptic errors. If your OLED remains blank or the Serial monitor spits out errors, here is how to troubleshoot.

The Exact Error String

If your I2C bus is locked, the address is wrong, or the wiring is faulty, the ESP32 Arduino Wire library will often output this exact error string to the Serial monitor:

[E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error 263 (I2C_ERROR_TIMEOUT)

Alternatively, if the Adafruit_SSD1306 library fails to allocate memory or find the device during display.begin(), our custom error handler will trigger, printing: SSD1306 allocation failed or I2C timeout.

The First Three Things to Check

  1. Verify the I2C Address (0x3C vs 0x3D): Most 0.96-inch SSD1306 OLEDs use 0x3C, but some variants (especially 1.3-inch SH1106/SSD1306 hybrids) default to 0x3D. Run an I2C scanner sketch to confirm your display's hex address. If it's 0x3D, change SCREEN_ADDRESS in the code.
  2. Check for Missing Pull-Up Resistors: The ESP32's internal I2C pull-ups are weak (typically ~50kΩ). If your OLED module lacks onboard pull-ups (common on cheap breakout boards), the bus will float, causing the I2C_ERROR_TIMEOUT. Add external 4.7kΩ pull-up resistors from SDA and SCL to 3.3V.
  3. Inspect 3.3V Rail Brownouts: Powering 4 LEDs and an OLED simultaneously from the ESP32's onboard 3.3V regulator can draw over 150mA. If the voltage drops below 3.0V, the I2C peripheral will reset mid-transaction. If your LEDs flicker when the OLED updates, power the OLED and LEDs from an external 3.3V buck converter, sharing a common ground with the ESP32.

Extending and Simplifying the Build

Depending on your project goals, you might need to scale this circuit up or strip it down.

How to Extend (8-Bit or Higher)

If you need to display the binary code for larger numbers (e.g., up to 255), wiring 8 individual LEDs consumes too many GPIO pins. Instead, use a 74HC595 8-bit shift register. You only need 3 ESP32 pins (Data, Clock, Latch) to control 8 LEDs. The bitwise logic remains identical; you simply shift the entire 8-bit byte into the 74HC595 using the shiftOut() function.

How to Simplify (Serial-Only)

If you don't have an OLED or want to reduce the BOM cost, delete the Adafruit library includes and the display object. Replace the updateOutputs() OLED logic with Serial.println(counter, BIN);. This prints the binary code for 4 directly to your PC's Serial Monitor as 100, saving flash memory and RAM.

Frequently Asked Questions

What is the 8-bit binary code for 4?

In an 8-bit system (like a standard byte in C++), the binary code for 4 is 00000100. The leading zeros are called 'padding'. Microcontrollers process data in fixed-width registers (8, 16, or 32 bits), so the hardware physically stores those leading zeros even if we omit them when writing on paper.

How do I write the binary code for 4 in C++ or Arduino?

You can write it using the binary literal prefix 0b. For example: int myVar = 0b0100;. Alternatively, you can use hexadecimal (0x04) or just standard decimal (4). The compiler converts all of these into the exact same machine code (00000100) during compilation. Using 0b0100 is preferred in embedded systems when you want to visually map the code to physical GPIO pins.

Why is the binary code for 4 written as 0100 instead of 100?

Mathematically, 100 in base-2 equals 4. However, in embedded engineering, we write it as 0100 to explicitly define the register width. If you are working with a 4-bit port, writing 0100 ensures you don't accidentally overwrite the 4th bit (Bit 3). It also aligns visually with hex nibbles, making it easier to convert between binary and hexadecimal in your head.

How does two's complement affect the binary code for -4?

Microcontrollers use 'two's complement' to represent negative numbers. To find the binary code for -4 in an 8-bit system, you start with positive 4 (00000100), invert all the bits (11111011), and add 1. The result is 11111100. Notice that the most significant bit (Bit 7) is 1, which is the universal hardware flag indicating a negative integer in signed data types.