Hashim Amin
Hashim Amin

Reputation: 43

Why does x86 assember allow a negative integer to be put into an unsigned variable?

When I run this in Visual Studios, it lets me successfully build the project.

.data
   val1 DWORD -1

Since DWORD is unsigned, shouldn't inputting a negative value result in an error?

Upvotes: 3

Views: 129

Answers (1)

Brendan
Brendan

Reputation: 37232

Everything is just a pattern of bits. For example (NASM syntax - the dd just means "data dword"), these values are the same pattern of bits:

    dd '4321'               ;Interpreted as ASCII characters
    dd 0x31323334           ;Interpreted as an unsigned hexadecimal number
    dd 825373492            ;Interpreted as a signed decimal number

..and this code is also the exact same pattern of bits, just interpreted as (32-bit) instructions:

    xor al,0x33
    xor dh,[ecx]

..and this code is still the exact same pattern of bits, interpreted as 16-bit instructions:

    xor al,0x33
    xor dh,[bx+di]

..and if you wanted you could interpret the same pattern of bits as a 32-bit floating point number (2.59315147e-9), or as a fixed point number (e.g. 12594.20001220703125), or as a binary coded decimal number (4321), or as a color ("dark grey with alpha" for RGBA), or as part of a sound, or...

How the pattern of bits are created doesn't really matter much. What matters is how the pattern of bits are used. For example, if you do add dword eax,[foo] then jb .somewhere then the branch instruction probably indicates that it was unsigned addition, but if you do add dword eax,[foo] then jl .somewhere then the branch instruction probably indicates that it was signed addition (even though the addition instruction is exactly the same for both signed and unsigned); but if you do fld dword [foo] then it's being used as a 32-bit floating point value, or...

Now; if you look at the way 2's compliment works you'll notice that (for 8-bit integers because I'm too lazy to type 32-bits) there's two ranges:

00000000b to 01111111b = 0 to +127, regardless of signed or unsigned
10000000b to 11111111b = +128 to +255 if unsigned, or -128 to -1 if signed

In other words, for 32-bit integers, 0xFFFFFFFF (unsigned) is the same pattern of bits as -1 (signed); and because the pattern of bits is the same it doesn't matter which version you use (except for code readability).

Upvotes: 4

Related Questions