Matey
Matey

Reputation: 197

bit operations in assembly

I would like to ask you how I can do bit operations &,<<,>>,| in assembly. I know about shift and Rotate opinion, but I don't know hot to do it with this. I'm able to write this in C but I don't know how to implement in assembly. Could you please help me with this?

EDIT: For Intel x86

Thanks

void shifting_in_C(unsigned short n)
{
    unsigned char a = n & 255;
    unsigned char b = n >>8;
    unsigned char c =  (n << 8) 
    unsigned char d = (n << 8) | 255;
}

Upvotes: 0

Views: 1440

Answers (2)

Joshua
Joshua

Reputation: 43188

void shifting_in_C(unsigned short n)
{
    unsigned char a = n & 255;
    unsigned char b = n >>8;
    unsigned char c =  (n << 8) 
    unsigned char d = (n << 8) | 255;
}


push ebx
; unsigned char a = n & 255;
mov al, [esp + 8]
; unsigned char b = n >>8;
mov bl, [esp + 9]
; unsigned char c =  (n << 8) 
xor cl, cl   ;(constant overflow)
; unsigned char d = (n << 8) | 255;
xor dl, dl   ;(constant overflow)
dec dl
pop ebx
ret

I think you want this:

unsigned short bswap16(unsigned short n)
{
    return ((n & 0xFF) << 8) | (n >> 8) & 0xFF;
}

mov ax, [esp + 4]
xchg al, ah
ret

Upvotes: 0

David Wohlferd
David Wohlferd

Reputation: 7483

You need to think a moment about what you are trying to accomplish. It's a common belief that "if I can write it in assembler, it will be faster." This seems like it would make sense since assembler is the language the processor actually speaks, right?

However that ignores the fact that the purpose of a compiler is to turn high level languages into assembler. And compilers know all sorts of tricks and quirks about how to wring the best performance out of processors that it would take you ages to master.

So if the goal is to make part of your code run faster by writing it in assembler, you need to be sure you can write assembler better than the wizards who write compilers. It can happen. But more commonly the code you write yourself is going to be slower.

But if the goal is to learn more about computers and assembler, then go for it.

That said...

The x86 assembler instructions you are looking for are pretty obvious once you start looking thru the available instructions. Here's an x86 instruction reference (not necessarily the best, just the first one google offered).

Looking at your example:

  • Paging thru the list we see the AND instruction described as "Logical AND"
  • SHR which they describe as "Shift" but more correctly would be described as "Shift Right."
  • SHL which is also described as "Shift" but is actually "Shift Left."
  • Your last example contains 2 operations. The first is another SHL, and the second is an OR.

If you plan to do much work in assembler, you should spend some time paging thru a reference to become familiar with the various instructions.

FWIW.

Upvotes: 3

Related Questions