Logical Operators
CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 24/90。
Logical 演算子は値全体に対して動作し、single result を返します: 1(true)または 0(false)。ビットごとに動作する bitwise 演算子とは異なり、Logical 演算子は値全体を true(non-zero)または false(zero)として扱います。
| 種類 | 例 | 結果 |
|---|---|---|
| ビット単位の AND | 4'b1010 & 4'b1100 | 4'b1000 (複数ビット) |
| 論理 AND | (4'b1010 && 4'b1100) | 1 (1ビット) |
利用可能な論理演算子
| 演算子 | 意味 | 説明 |
|---|---|---|
&& | 論理 AND | オペランドが both true(non-zero)である場合に True |
|| | 論理 OR | オペランドの at least one が true である場合に True |
! | 論理 NOT | オペランドが false(zero)である場合に True |
仕組み
論理 AND(<strong>&&</strong>):
(5 && 3) // 1 (両方とも非ゼロ)
(5 && 0) // 0 (2つ目がゼロ)
(0 && 0) // 0 (両方ともゼロ)論理 OR(<strong>||</strong>):
(5 || 3) // 1 (少なくとも1つは非ゼロ)
(5 || 0) // 1 (最初の非ゼロ)
(0 || 0) // 0 (両方ゼロ)論理 NOT(<strong>!</strong>):
!5 // 0 (非ゼロは false になる)
!0 // 1 (ゼロは true になる)コード例
module logical_demo;
reg [3:0] a, b;
reg and_res, or_res, not_res;
initial begin
a = 5;
b = 0;
and_res = (a && b); // 5 && 0 = 0
or_res = (a || b); // 5 || 0 = 1
not_res = !a; // !5 = 0
$display("5 && 0 = %d", and_res);
$display("5 || 0 = %d", or_res);
$display("!5 = %d", not_res);
$finish;
end
endmodule出力:
5 && 0 = 0
5 || 0 = 1
!5 = 0一般的な使用方法
論理演算子はif文や条件で使用されます:
if (a && b) // a と b の両方が非ゼロの場合に真
$display("Both true");
if (a || b) // 少なくとも1つが非ゼロの場合に真
$display("At least one true");
if (!reset) // reset が 0 のときに真
$display("Reset is inactive");チャレンジ
各タスクに対する正しい論理式を書いてください。
実行すること:
value1ANDvalue2が both true であるか Check し、and_outに格納するvalue1ORvalue2のいずれかが true であるか Check し、or_outに格納するvalue1が false であるか Check し、not_outに格納する
自分で試してみよう
module logical_challenge;
reg [3:0] value1, value2;
reg and_out, or_out, not_out;
initial begin
value1 = 4'd12;
value2 = 4'd5;
and_out = ______; // value1 && value2
or_out = ______; // value1 || value2
not_out = ______; // !value1
$display("%d && %d = %d", value1, value2, and_out);
$display("%d || %d = %d", value1, value2, or_out);
$display("!%d = %d", value1, not_out);
$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オンラインコンパイラ