Modulo Operator
Teil des Abschnitts Grundlagen der Verilog-Journey von Coddy. Lektion 20 von 90.
Ein weiterer grundlegender arithmetischer Operator ist der Modulo-Operator (%). Er liefert den Rest nach einer Division.
Wenn du eine Zahl durch eine andere teilst, teilt dir der Modulo-Operator mit, was übrig bleibt.
| Ausdruck | Ergebnis | Erklärung |
|---|---|---|
10 % 3 | 1 | 10 ÷ 3 = 3 mit Rest 1 |
15 % 4 | 3 | 15 ÷ 4 = 3 mit Rest 3 |
8 % 2 | 0 | 8 ÷ 2 = 4 mit Rest 0 |
Codebeispiel
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
endmoduleHäufige Verwendungen
Prüfen, ob eine Zahl gerade oder ungerade ist:
if (number % 2 == 0)
$display("Even");
else
$display("Odd");Einen Zähler umlaufen lassen (0 bis 9, dann zurück zu 0):
count = (count + 1) % 10;Erhalte die letzte Ziffer einer Zahl:
last_digit = value % 10; // 123 % 10 = 3Aufgabe
Berechne die Reste für jeden Ausdruck.
Was zu tun ist:
- Berechne
17 % 5und speichere das Ergebnis inmod1 - Berechne
22 % 7und speichere das Ergebnis inmod2 - Berechne
14 % 4und speichere das Ergebnis inmod3
Probier es selbst
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
endmoduleDiese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Grundlagen
1Einführung
Was ist VerilogHardware vs. SoftwareIhr erstes ModulKommentareAbstraktionsebenen des Designs4Operators 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Übe selbstständig: Online-Verilog-Compiler