hello,
this is my code and for some reason it does not work :/ could someone tell me whats going wrong?

;sum of all powers of 2 lower or equal to 2^n
;example n=4 => 2+4+8+16=30

.386
.model flat, stdcall
option casemap: none

include \masm32\include\windows.inc
include \masm32\include\masm32.inc
include \masm32\include\kernel32.inc

includelib \masm32\lib\masm32.lib
includelib \masm32\lib\kernel32.lib

.data
    good db "that is correct :)",0
    bad  db "that is not correct :(",0
    sum sdword 0

.code
start:
    mov ecx,4           ;counter
    xor eax,eax         ;eax will contain sum

    _label:
        mov bx,1        ;stores 1 in bx
        ;(mov cl,ecx)
        shl bx,cl       ;bx=1*2^cl
        add eax,ebx     ;add bx to eax
        dec ecx         ;lower counter
        jnz _label      ;loop until ecx=0
        push eax        ;eax=16+8+4+2=30
        pop sum         ;pop value of eax in sum
        cmp sum,30      ;compare sum to 30
        jz _good        ;if sum=30 jump to _good

    _bad:
        invoke StdOut,addr bad
        jmp _quit

    _good:
        invoke StdOut,addr good

    _quit:
        invoke ExitProcess,0
end start

edit: the code gets compiled and runs good. but it is saying that the sum is not 30. so there must be something wrong in my 'math' part.

There is nothing wrong with the calculation part

    global  _start

    section .const
  Sum       dd  0

    section .text

   _start   mov ecx, 4
            xor eax, eax

      .L0   mov  bx, 1
            shl  bx, cl
            add eax, ebx
            dec ecx
            jnz .L0             

            cmp eax, 30     ; Result in EAX is 1EH

     .Done  xor rdi, rdi
            mov al, 60
            syscall

My example is done on Ubuntu 12.04 using NASM. It has been awhile since I've used MASM, so the only question I'd have is what is in line 18 sdword or could you be in line 34 actually comparing 48 (30H).

Edited 3 Years Ago by ShiftLeft

well i altered my code now and it still does not work

_label:
        mov bx,1        ;stores 1 in bx
        shl bx,cl       ;bx=1*2^cl
        add eax,ebx     ;add bx to eax
        dec ecx         ;lower counter
        jnz _label      ;loop until ecx=0

        cmp eax,1EH     ;compare sum to 30
        jz _good        ;if sum=30 jump to _good

There's most likely some memory junk in the upper 16 bits of the ebx register,
so change mov bx,1 to mov ebx,1

Edited 3 Years Ago by nullptr

Comments
correct
This article has been dead for over six months. Start a new discussion instead.