Negative Numbers
CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 16/90。
Verilogでは、negative numbersはtwo's complement形式を使用して表現されます。two's complementは、binaryでpositive numbersとnegative numbersの両方を表現する方法です。最上位bit(MSB)は符号を示します:
- 0 = positive number
- 1 = negative number
Two's Complement の計算方法
数値の Two's Complement を求めるには:
- 正の数を 2 進数で書く
- すべての bit を反転する(0 は 1 に、1 は 0 になる)
- 1 を加える
例:4ビットで -5 を表す
| 手順 | 操作 | 結果 |
|---|---|---|
| 1 | 2進数での正の 5 | 0101 |
| 2 | すべてのビットを反転 | 1010 |
| 3 | 1を加算 | 1011 |
4ビットの two's complement における -5 は <strong>4'b1011</strong>
Verilogで負の数を書く
10進形式を使用して、負の数を直接記述できます。
reg signed [3:0] a;
a = -5; // Verilogは自動的に2の補数を使用しますビット幅が指定された二進数では、二の補数の値を記述する必要があります:
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を使用すると automatically に機能します - MSB が符号を決定します: 1 = negative、0 = positive
チャレンジ
正しい two's complement の値を書いてコードを完成させてください。
行うこと:
aを、4-bit two's complement binary を使用して -3 に設定するbを、4-bit two's complement binary を使用して -8 に設定するcを、4-bit two's complement binary を使用して -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オンラインコンパイラ