Menu
Coddy logo textTech

Binary Representation

Part of the Fundamentals section of Coddy's Verilog journey — lesson 13 of 90.

In Verilog, we work with digital circuits that understand only 0 and 1. These are represented in binary.

Binary uses only two digits: 0 and 1. Each binary digit is called a bit.

DecimalBinaryBits
001 bit
111 bit
2102 bits
3112 bits
41003 bits
51013 bits

Writing Binary in Verilog

To write binary numbers in Verilog, use the prefix 'b:

4'b1010    // 4-bit binary 1010 (decimal 10)
8'b11110000 // 8-bit binary 11110000 (decimal 240)
2'b01      // 2-bit binary 01 (decimal 1)

The number before 'b tells Verilog how many bits the value has.

How to Convert Decimal to Binary

Divide the decimal number by 2 repeatedly and read the remainders from bottom to top.

Example: Convert 9 to binary

StepDivisionQuotientRemainder
19 ÷ 241
24 ÷ 220
32 ÷ 210
41 ÷ 201

Read remainders from last to first: 1001

9 = 4'b1001

Example in Code

module binary_example;
  reg [3:0] a;
  
  initial begin
    a = 4'b1010;     // Binary 1010 = decimal 10
    $display("a = %b (binary)", a);
    $display("a = %d (decimal)", a);
    $display("a = %h (hex)", a);
    $finish;
  end
endmodule

Output:

a = 1010 (binary)
a = 10 (decimal)
a = a (hex)
challenge icon

Challenge

Complete the code by writing the missing binary values.

What to do:

  1. Write binary for decimal 5 (4 bits)
  2. Write binary for decimal 14 (4 bits)

Cheat sheet

Binary uses only 0 and 1. Each digit is a bit.

Write binary in Verilog with the 'b prefix — the number before it specifies the bit width:

4'b1010    // 4-bit binary = decimal 10
8'b11110000 // 8-bit binary = decimal 240

Display formats: %b (binary), %d (decimal), %h (hex).

Decimal to binary: divide by 2 repeatedly, read remainders bottom to top.

// 9 ÷ 2 → 4 r1 → 2 r0 → 1 r0 → 0 r1  ⟹  1001
// 9 = 4'b1001

Try it yourself

module binary_challenge;
  reg [3:0] a, b;
  
  initial begin
    // Write binary for decimal 5 (4 bits)
    a = 4'b______;
    
    // Write binary for decimal 14 (4 bits)
    b = 4'b______;
    
    $display("5 = %b", a);
    $display("14 = %b", b);
    $finish;
  end
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals