Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NASM shift operators

How would you go about doing a bit shift in NASM on a register? I read the manual and it only seems to mention these operators >>, <<. When I try to use them NASM complains about the shift operator working on scalar values. Can you explain what a scalar value is and give an example of how to use >> and <<. Also, I thought there were a shr or shl operators. If they do exist can you give an example of how to use them? Thank you for your time.

like image 682
Hudson Worden Avatar asked Mar 31 '12 23:03

Hudson Worden


People also ask

Which are shift operators?

In mathematics, and in particular functional analysis, the shift operator also known as translation operator is an operator that takes a function x ↦ f(x) to its translation x ↦ f(x + a). In time series analysis, the shift operator is called the lag operator.

How many types of shift operators are there?

Shift operators are classified into two types based on the shifting position of the bits.

What does shift operations do?

A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. The next table summarizes the shift operators available in the Java programming language. Each operator shifts the bits of the first operand over by the number of positions indicated by the second operand.

What does shift do in assembly?

Shifting means to move bits right and left inside an operand. A logical shift fills the newly created bit position with zero. If we do a single logical right shift on 11001111, it becomes 011001111.


2 Answers

<< and >> are for use with integer constants only. This is what it means by "scalar value". You can shift the value in a register using the shl or shr instructions. They are used to shift the value in a register left or right, respectively, a given number of bits.

The first line in this example shifts the value in ax left 4 bits, which is the same as multiplying it by 16. The second line shifts the value in bx right by 2 bits, which is the same as integer division by 4.

shl ax, 4
shr bx, 2

You can also use cl to indicate the number of bits to shift, instead of a constant. For more information on these and related instructions, see this page.

like image 120
ughoavgfhw Avatar answered Oct 06 '22 00:10

ughoavgfhw


Piggy-backing on ughoavgfhw's answer... to use << and >>, use them directly on constants:

MOV EAX, 1 << 2    ; Puts 4 into EAX
MOV EAX, 2 << 2    ; Puts 8 into EAX
MOV EAX, 8 >> 1    ; Puts 4 into EAX
like image 34
Landshark666 Avatar answered Oct 05 '22 23:10

Landshark666