Shift Operators
CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 26/90。
シフト演算子は、ベクトル内のビットを左または右に移動します。
使用可能なシフト演算子
| 演算子 | 操作 | 説明 |
|---|---|---|
<< | 論理左シフト | ビットを左にシフトし、0で埋めます |
>> | 論理右シフト | ビットを右にシフトし、0で埋めます |
<<< | 算術左シフト | 論理左シフトと同じです |
>>> | 算術右シフト | 右にシフトし、符号ビットを保持します |
仕組み
左シフト(<strong><<</strong>):
8'b00001010 << 2 = 8'b00101000ビットは左に移動します。右側はゼロで埋められます。
右シフト(<strong>>></strong>):
8'b00001010 >> 2 = 8'b00000010ビットは右に移動します。左側はゼロで埋められます。
コード例
module shift_demo;
reg [7:0] original, left_shift, right_shift;
initial begin
original = 8'b00001010;
left_shift = original << 2; // 00001010 → 00101000
right_shift = original >> 2; // 00001010 → 00000010
$display("original = %b", original);
$display("<< 2 = %b", left_shift);
$display(">> 2 = %b", right_shift);
$finish;
end
endmodule出力:
original = 00001010
<< 2 = 00101000
>> 2 = 00000010算術右シフト(>>>)
signed 数値の場合、算術右シフトは符号ビットを保持します。
reg signed [7:0] a;
a = -5; // 11111011
a >>> 2 = 11111110 // まだ負のまま論理シフト(>>)では 0 で埋められ、符号が失われます。
一般的な用途
2のべき乗を掛ける(左シフト):
x << 1 // 2倍する
x << 2 // 4倍する
x << 3 // 8倍する2のべき乗で割る(右シフト):
x >> 1 // 2で割る
x >> 2 // 4で割る
x >> 3 // 8で割るフィールドを抽出する:
// 8ビット値からビット5-2を取得
field = (data >> 2) & 4'b1111;チャレンジ
各タスクに対する正しいシフト式を書いてください。
行うこと:
aを 3 ビット左にシフトし、left_resultに格納するaを 1 ビット右にシフトし、right_resultに格納する- (算術)
bを 2 ビット右にシフトし、arith_resultに格納する
自分で試してみよう
module shift_challenge;
reg [7:0] a;
reg signed [7:0] b;
reg [7:0] left_result, right_result;
reg signed [7:0] arith_result;
initial begin
a = 8'b00010001;
b = -8'sd16; // 2進数で11110000
left_result = ______; // aを3ビット左シフト
right_result = ______; // aを1ビット右シフト
arith_result = ______; // bを2ビット右シフト(算術)
$display("a = %b", a);
$display("a << 3 = %b", left_result);
$display("a >> 1 = %b", right_result);
$display("b = %b", b);
$display("b >>> 2 = %b", arith_result);
$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オンラインコンパイラ