Negative Numbers
Coddy Verilog 여정의 기초 섹션에 포함된 레슨. 90개 중 16번째.
Verilog에서 negative numbers는 two's complement 형식을 사용하여 표현됩니다. Two's complement는 이진수로 positive 및 negative numbers를 모두 표현하는 방법입니다. 최상위 비트(MSB)는 부호를 나타냅니다:
- 0 = positive number
- 1 = negative number
two's complement 계산 방법
숫자의 two's complement를 구하려면:
- positive 숫자를 이진수로 작성합니다
- 모든 bit를 반전합니다 (0은 1이 되고, 1은 0이 됩니다)
- 1을 더합니다
예: 4비트로 -5 표현하기
| 단계 | 연산 | 결과 |
|---|---|---|
| 1 | positive 5를 이진수로 표현 | 0101 |
| 2 | 모든 bit 반전 | 1010 |
| 3 | 1 더하기 | 1011 |
4비트 two's complement에서 -5는 <strong>4'b1011</strong>입니다.
Verilog에서 negative 숫자 작성하기
decimal 형식을 사용하여 negative 숫자를 직접 작성할 수 있습니다:
reg signed [3:0] a;
a = -5; // Verilog는 자동으로 2의 보수를 사용합니다크기가 지정된 이진수의 경우, two's complement 값을 작성해야 합니다:
a = 4'b1011; // This is -5 in 4-bit two's complement부호 있는 값과 부호 없는 값 비교
기본적으로 Verilog는 숫자를 부호 없는 값으로 처리합니다. 음수를 다루려면 신호를 signed로 선언하세요:
reg signed [3:0] negative; // -8부터 7까지 저장할 수 있음
reg [3:0] positive; // 0부터 15까지 저장할 수 있음부호 있는 숫자의 범위
N비트의 경우, 부호 있는 숫자는 다음을 나타낼 수 있습니다.
- 최솟값: -2^(N-1)
- 최댓값: 2^(N-1) - 1
| 비트 | 범위 |
|---|---|
| 4비트 | -8에서 7까지 |
| 8비트 | -128에서 127까지 |
| 16비트 | -32768에서 32767까지 |
중요 참고 사항
signed키워드를 사용하여 음수 처리를 활성화하세요signed가 없으면 Verilog는 모든 값을 양수로 처리합니다
- signed를 사용할 때 two's complement 산술은 automatically 작동합니다
- MSB가 부호를 결정합니다: 1 = negative, 0 = positive
챌린지
올바른 two's complement 값을 작성하여 코드를 완성하세요.
할 일:
a를 4-bit two's complement 이진수를 사용하여 -3으로 설정하세요b를 4-bit two's complement 이진수를 사용하여 -8로 설정하세요c를 4-bit two's complement 이진수를 사용하여 -1로 설정하세요
직접 해보기
module negative_challenge;
reg signed [3:0] a, b, c;
initial begin
a = 4'b______; // -3 in 4-bit two's complement
b = 4'b______; // -8 in 4-bit two's complement
c = 4'b______; // -1 in 4-bit two's complement
$display("a = %d", a);
$display("b = %d", b);
$display("c = %d", c);
$finish;
end
endmodule이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Operators Part 1
Arithmetic OperatorsModulo OperatorComparison OperatorsRecap - Simple MathBitwise Operators7Assign And Gates
Continuous AssignmentAssign With OperatorsBuilt In Gate PrimitivesAND OR NOT GatesXOR XNOR GatesRecap - Logic Gate Circuit10Decision Making
If StatementIf - ElseRecap - Simple ComparatorCase StatementCasex And CasezRecap - ALU Design5Operators Part 2
Logical OperatorsReduction OperatorsShift OperatorsConcatenation OperatorConditional OperatorRecap - Operator Challenge3Number System
Binary RepresentationSized NumbersUnsized NumbersNegative NumbersSpecial Values X And ZRecap - Number Formats6Modules
Module StructureInput And Output PortsInout PortsModule InstantiationPort Mapping By NamePort Mapping By OrderRecap - Build A Module9Procedural Blocks
Always BlockInitial BlockSensitivity ListBlocking AssignmentNon Blocking AssignmentRecap - Always vs Initial15Traffic Light Controller
Defining The StatesState Machine Logic직접 연습해 보세요: 온라인 Verilog 컴파일러