SKKU SW/Computer Architecture

[컴퓨터구조] Logical operations

효딩 2023. 4. 14. 17:21
Operation C JAVA RISC-V
Bitwise AND & & and, andi
Bitwise OR | | or, ori
Bitwise XOR ^ ^ xor, xori
Bitwise NOT ~ ~ xor, xori
Shift left << << slli
Shift right >> >>> srli

 

<AND Operations>

and x9, x10, x11

 

<OR Operations>

or x9, x10, x11

 

<XOR Operations>

xor x9, x10, x11

쉽게 생각하면 같으면 0, 다르면 1

if x11 = -1 (0xFFFFFFFF), x9 = ~x10

(x11이 모든 비트가 다 1이라면 xor 연산을 통해 1은 0으로 0은 1로 바뀔 것이기 때문)

 

<NOT Operations>

RISC-V has xori

a XORI -1 == NOT a

 

Pseudo-instruction: not

not x10, x11

-> xori x10, x11, -1

 

<Basic Shifting>

Shift types

1. Logical(or unsigned) shift

Logical shifts are useful to perform multiplication or division of unsigned integer by powers of two

2. Arithmetic(or signed) shift

Logical shifts are useful to perform multiplication or division of signed integer by powers of two

shift left의 경우는 같은데, shift right는 logical, arithmetic 각각의 값이 다르니 주의할 것.

 

Shift directions

1. Left (multiply by powers of 2)

2. Right (divide by powers of 2)

 

<Shift operations>

slli, srli

(shift left logical operation with immediate value, shift right logical operation with immediate value)

ex) slli rd, rs1, 4

 

srai

(shift right arithmetic) - extend the sign bit

useful for dividing 2's complement numbers

 

주의: slai는 존재하지 않는다.

앞서 설명했듯이, left shift는 shift, arithmetic의 결과가 동일하기 때문이다.

 

sll, srl, sra

ex) sll rd, rs1, rs2

(rs1의 값을 rs2만큼 왼쪽으로 shift해서 rd에 저장)

여기서도 마찬가지로 sla는 존재하지 않는다.

shift by the amount held in the lower 5 bits of register rs2

이게 무슨 말이나면 rs2 값의 앞부분은 잘라 먹고 lower 5 bits만 가져와서 그만큼 shift한다는 거다.

 

이전 글에서 공부했던 load operation인 li도 함께 적용해서 보자면

li x10, 200

li x11, 100

sll x12, x10, x11

일단 200을 x10에 저장, 100을 x11에 저장한뒤

100 = 64 + 32 + 4 니까 이를 32비트로 나타내면 0000 0000 0000 0000 0000 0000 0110 0100

그 중 하위 5비트만 가져온다면 00100 -> 10진수로 나타내면 4

x10에 저장되어 있는 200을 4만큼 left shift하겠다는 뜻!

 

200 = 128 + 64 + 8 이니까 0000 0000 0000 0000 0000 0000 1100 1000

이를 4만큼 left shift 하면?

0000 0000 0000 0000 0000 1100 1000 0000

사실 이렇게 하나씩 계산할 필요 없이 4만큼 left shift는 2^4, 즉 16을 곱한 것과 같으므로

200 x 2^4 = 3200으로 계산하면 된다.

 

shift right arithmetic 값은 "round down"한다.