From Analog to Digital: Signal Simulation



This content originally appeared on DEV Community and was authored by Simon chauveau

Ever wondered how sound—like your voice or music—is transformed into digital data that can be stored on a computer or phone? In this post, we’ll explore how it works using a simple MATLAB simulation.

Simple simulation

Step 1 : Creation of Analog Signal
First, we create a sine wave (like a pure tone) at 100 Hz:

t = 0:0.0001:0.01;       % very fine step (continuous-like time)
f = 100;                 % frequency = 100 Hz
x_analog = sin(2*pi*f*t);

Let’s visualize it:

figure;
plot(t, x_analog, 'LineWidth', 1.5);
title('Analog Signal (Sine Wave)');
xlabel('Time (s)'); ylabel('Amplitude');

Analog Signal

This waveform represents our original sound.

Step 2 : Sampling the Signal
Sampling is like taking snapshots of the signal at regular intervals. The higher the sampling frequency, the better the quality.

I tested three sampling frequencies:

  • 150 Hz : Too slow
  • 200 Hz : Just enough (Nyquist rate)
  • 1000 Hz : Good

For this example, we use 1000 Hz:

Fs = 1000;               % Sampling frequency = 1 kHz
Ts = 1/Fs;               % Sampling period
n = 0:Ts:0.01;           % Discrete sample points
x_sampled = sin(2*pi*f*n);

Visualizing the sampled signal:

figure;
stem(n, x_sampled, 'filled');
title('Sampled Signal');
xlabel('Time (s)'); ylabel('Amplitude');

Signal Sample

Step 3 : Quantization
Quantization rounds each sample to the nearest level. More levels = better detail.

I tested:

  • 3 bits : 8 levels
  • 4 bits : 16 levels
  • 6 bits : 64 levels

Here’s the 4-bit version:

bits = 4;                           % Number of bits
levels = 2^bits;                    % Quantization levels
x_min = min(x_sampled);
x_max = max(x_sampled);
q_step = (x_max - x_min)/levels;    % Step size

x_index = round((x_sampled - x_min)/q_step); % Map samples to indices
x_quantized = x_index*q_step + x_min;        % Map back to amplitude

Visualizing the quantized signal:

figure;
stem(n, x_quantized, 'filled');
title(['Quantized Signal (' num2str(bits) '-bit)']);
xlabel('Time (s)'); ylabel('Amplitude');

Signal quantized

Step 4 : Encoding (Binary)
Now we convert each quantized value into binary:

binary_codes = dec2bin(x_index, bits); % Convert indices to binary words

To display the first 10 samples:

disp('--- First 10 encoded samples ---');
disp(binary_codes(1:10));

Step 5 : Digital Stream
Finally, we combine all binary codes into one bitstream:

bitstream = reshape(binary_codes.',1,[]); % Concatenate into one string

Display the first 40 bits:

disp('--- First 40 bits of the stream ---');
disp(bitstream(1:40));

Text Result

This bitstream is what computers and phones use to store and process sound.

GitHub

You can find the full MATLAB code and result images on my GitHub repository:


This content originally appeared on DEV Community and was authored by Simon chauveau