---
# System prepended metadata

title: 04. 變數處理
tags: [語法教學, Verilog]

---

# Verilog 變數處理

## 1. 變數宣告

### ● 位元宣告
```verilog
wire a; // 1-bit wire
```

### ● 向量宣告
```verilog
wire [7:0] vector; // vector 為 8-bit wire bus
```

### ● 陣列宣告
```verilog
reg [7:0] mem [0:3]; // mem 為 4x8 bits 記憶空間
```

### ● 有號數宣告
- **Verilog 預設為無號數 (unsigned)**
```verilog
wire signed [2:0] a = -1; // a = ~3'b001 + 3'b001 = 3'b111
```

### ● 訊號狀態
> [!Tip]
> **`0`：low signal**  
> **`1`：high signal**  
> **`x`：unknown signal**  
> **`z`：high impedance**

### ● 進制種類
```verilog
wire [7:0] bin = 8'b1101_0110;
wire [7:0] oct = 8'o326;
wire [7:0] hex = 8'hD6;
wire [7:0] dec = 8'd214;
```


---
## 2. 基礎位元控制

### (1) 位元選擇 (Bit Select)

```verilog
wire [7:0] a = 8'b11001010;
assign b = a[7];   // b = 1'b1
assign c = a[5:2]; // c = 4'b0010
```

### (2) ==特殊位元選擇==

```verilog
assign d = a[sel+:4]; // {a[sel+3], a[sel+2], a[sel+1], a[sel]}
assign e = a[sel-:4]; // {a[sel], a[sel-1], a[sel-2], a[sel-3]}
```

### (3) 位元移動 (Shift)

```verilog
wire [7:0] a = 8'b11000101;
assign shl = a << 1; // shl = 8'b1000_1010
assign shr = a >> 1; // shr = 8'b0110_0010
```

---

## 3. ==進階位元控制==

### (1) 位元組合 (Concatenation)

```verilog
wire [3:0] a = 4'b1010;
wire [3:0] b = 4'b1100;
assign c = {a, b}; // c = 8'b1010_1100
```

### (2) 重複運算子 (Replication Operator)

```verilog
wire [7:0] pattern = {2{4'b1100}}; // pattern = 8'b1100_1100
```

### ● 一元歸約 (Unary Reduction)

- **對一條 bus 的每個位元做相同邏輯運算**

| 名稱               |   運算子   | 功能                            |
|:------------------ |:----------:|:------------------------------- |
| **Reduction OR**   | **`\|a`**  | 對 bus a 的每個位元做 OR 運算   |
| **Reduction AND**  |  **`&a`**  | 對 bus a 的每個位元做 AND 運算  |
| **Reduction XOR**  |  **`^a`**  | 對 bus a 的每個位元做 XOR 運算  |
| **Reduction NOR**  | **`~\|a`** | 對 bus a 的每個位元做 NOR 運算  |
| **Reduction NAND** | **`~&a`**  | 對 bus a 的每個位元做 NAND 運算 |
| **Reduction XNOR** | **`~^a`**  | 對 bus a 的每個位元做 XNOR 運算 |

```verilog
wire [3:0] a = 4'b1010;

assign result_or  = |a; // 1 | 0 | 1 | 0 = 1
assign result_and = &a; // 1 & 0 & 1 & 0 = 0 
assign result_xor = ^a; // 1 ^ 0 ^ 1 ^ 0 = 0
```
