Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a signed integer is neg or pos?

Tags:

x86

assembly

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

like image 340
Yonk Avatar asked Oct 25 '10 17:10

Yonk


People also ask

How do you know if an integer is positive or negative?

If the Integer is greater than zero then it is a positive integer. If the number is less than zero then it is a negative integer. If the number is equal to zero then it is neither negative nor positive.

Which flag is used to check if a number is positive or negative?

oVerflow (V flag): V=1 when the result of : Positive + Positive is a Negative.

Can signed int be negative?

This attribute of being positive, negative, or zero is called the number's sign. By default, integers are signed, which means the number's sign is stored as part of the number (using a single bit called the sign bit). Therefore, a signed integer can hold both positive and negative numbers (and 0).


1 Answers

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
like image 89
ruslik Avatar answered Oct 13 '22 16:10

ruslik