Electronics > Beginners

C learning

<< < (6/6)

andri:

--- Quote ---But a person who has used ASM would definitely know that it can be optimized...


--- Code: ---int a, c;

a=450;
c= a>>5;

--- End code ---

--- End quote ---

This is not really about knowing assembly, rather about general base-2 calculations.

In fact, any decent C compiler will happily do it for you. Example: I compiled with gcc 4.1.2 (with flags -m32 -march=i386 for simplicity)  the following function:


--- Code: ---int divide (unsigned int a) {
        unsigned int b = 32;
        return a / b;
}

--- End code ---

(I had to move it into a function, otherwise the compiler optimized the whole division away.)

With -O0 optimizations (everything turned off) it indeed compiles into rather dumb division:

--- Code: ---divide:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $16, %esp
        movl    $32, -4(%ebp)
        movl    8(%ebp), %eax
        movl    $0, %edx
        divl    -4(%ebp)
        leave
        ret

--- End code ---

However, even with -O1 it does the optimization for us:

--- Code: ---divide:
        pushl   %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %eax
        shrl    $5, %eax
        leave
        ret

--- End code ---

(Quick guide to i386 assembly: "shrl" is logical shift right, "divl" is unsigned division).

migsantiago:

--- Quote from: andri on September 17, 2010, 01:45:32 am ---This is not really about knowing assembly, rather about general base-2 calculations.

--- End quote ---

Yeah, I was just looking for a simple example. Sorry.  :P

joelby:

--- Quote from: migsantiago on September 17, 2010, 01:54:10 am ---Yeah, I was just looking for a simple example. Sorry.  :P

--- End quote ---

Well, one that applies to the MSP430 - the processor has instructions that handle BCD numbers, but there's no standard way to represent these in C so the compiler isn't able to recognise that these instructions could be used. The solution is pretty easy - use the inline assembly code examples that TI helpfully provide.

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod