12

I am new to x86 assembly language, I have a signed integer saved in register eax, and I want to check if the number is negative or positive. To do that, I used bt instruction to check the first bit.

Here is what I did:

bt eax,0
jnc isNegative

bt carries the first bit to carry flag, and I used jnc to check if carry flag is 0 or 1. If it's 1, it should be a negative number, and does negative instructions... however, the output is unpredictable, sometimes I have a positive and it recognize it as a negative number. Am I doing something wrong?

EDIT: I just realized it could have something to do with endianess. It is actually checking the last bit instead of the first bit. Let me try use bt, 7

nrz
  • 9,959
  • 4
  • 36
  • 69
Yonk
  • 155
  • 1
  • 2
  • 6

3 Answers3

20

The value is negative if the MSB is set. It can be checked with

test eax, 0x80000000
jne is_signed

or, simplier:

test eax, eax
js signed

or for byte case:

test al, al
js is_signed
; or
test eax, 80h
jne is_signed
ruslik
  • 13,918
  • 1
  • 33
  • 38
5

You can use the jge and cmp instructions:

cmp eax, 0
jl isNegative
nmichaels
  • 45,418
  • 12
  • 95
  • 127
1

Your current solution checks if the number is even or odd, instead test the 31st bit:

bt eax, 31
jc number_is_negative

Or you can compare the number to zero, and test whether it's greater than or equal to it.

main:
    ...
    cmp eax, 0 ; Compare the number to zero
    jge .number_is_positive ; If it's positive jump to .number_is_positive
    ; And only arrive here if a number is negative
    ...
.number_is_positive:
    ; Yay! number is positive
    ...
Joe D
  • 2,674
  • 2
  • 27
  • 25