Modulo Operator
CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 20/90。
もう1つの基本的な算術演算子は剰余演算子(%)です。割り算の後の余りを返します。
ある数を別の数で割ると、剰余演算子は何が残るかを示します。
| 式 | 結果 | 説明 |
|---|---|---|
10 % 3 | 1 | 10 ÷ 3 = 3、余りは1 |
15 % 4 | 3 | 15 ÷ 4 = 3、余りは3 |
8 % 2 | 0 | 8 ÷ 2 = 4、余りは0 |
コード例
module modulo_demo;
reg [7:0] result;
initial begin
result = 10 % 3;
$display("10 %% 3 = %d", result); // 1
result = 15 % 4;
$display("15 %% 4 = %d", result); // 3
result = 8 % 2;
$display("8 %% 2 = %d", result); // 0
$finish;
end
endmodule一般的な用途
数値が偶数か奇数かを確認する:
if (number % 2 == 0)
$display("Even");
else
$display("Odd");カウンターを循環させる(0 から 9、次に 0 に戻る):
count = (count + 1) % 10;数値の最後の桁を取得する:
last_digit = value % 10; // 123 % 10 = 3チャレンジ
各式の余りを計算してください。
すること:
17 % 5を計算し、mod1に格納します22 % 7を計算し、mod2に格納します14 % 4を計算し、mod3に格納します
自分で試してみよう
module modulo_challenge;
reg [7:0] mod1, mod2, mod3;
initial begin
mod1 = ______; // 17 % 5
mod2 = ______; // 22 % 7
mod3 = ______; // 14 % 4
$display("17 %% 5 = %d", mod1);
$display("22 %% 7 = %d", mod2);
$display("14 %% 4 = %d", mod3);
$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オンラインコンパイラ