Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x86 assembly, little endianness not being followed(or is it?) (Linux)

I am new to assembly language programming and I wrote a small program to print the integer using sys_write system call. Here's my code :

section .data

N: dw 216
chr: dw ,0,0,0,0x0a

section .bss

section .text

  global _start

_start:
            xor ax, ax
            mov ax, word [N]
            mov cx, 10 
            mov ebx,4

shift_while: div cx 
             add dx, 0x0030
             mov word [chr+ebx],dx
             sub ebx, 2 
             xor dx, dx
             cmp ax, 0
             jne shift_while
             call printchar

exit:        mov eax, 1
             mov ebx, 0
             int 80h


printchar:  pushad
            mov eax, 4
            mov ebx, 1
            mov ecx, chr
            mov edx, 8
            int 80h
            popad
            ret

I have hard coded 216, the number to be printed and I am getting the correct output. However what I am bemused by is the "mov word [chr+ebx],dx" instruction. dx contains 0x0032 in the first iteration so at the address [chr+ebx] this value should be stored as 32 00 (hex). But when I examined chr memory using gdb, it showed:

(gdb) x /5hx 0x80490d2
0x80490d2 <chr>:    0x0032  0x0031  0x0036  0x000a

what I expected was 0x3200 0x3100 0x3600 x0a00 and thought I'd have to do further memory manipulation to get the right result. Am I going wrong somewhere with this. Are there things I can't seem to see. I'd really appreciate a little help here. This is my first first post on stackoverflow.

like image 340
san216 Avatar asked Dec 10 '22 11:12

san216


2 Answers

It's just a representation thing - what you have in memory from a byte-wise perspective is

32 00 31 00 26 00 0a 00

but when you view this as 16 bit values it's

0032 0031 0026 000a

Similarly, if you viewed it as 32 bit values it would be:

00310032 000a0026

Such is the weirdness of little endianness. ;-)

like image 70
Paul R Avatar answered Jan 18 '23 08:01

Paul R


gdb is helping you out here.

You asked for the h (halfword) format, on a little-endian platform, so it is decoding the memory as 16-bit little endian-values for you.

If you use the b format instead, you'll see something more like you expected.

like image 20
Matthew Slattery Avatar answered Jan 18 '23 07:01

Matthew Slattery