Author Topic: C learning  (Read 11904 times)

0 Members and 1 Guest are viewing this topic.

Offline andri

  • Contributor
  • Posts: 10
Re: C learning
« Reply #25 on: September 17, 2010, 01:45:32 am »
Quote
But a person who has used ASM would definitely know that it can be optimized...

Code: [Select]
int a, c;

a=450;
c= a>>5;

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: [Select]
int divide (unsigned int a) {
        unsigned int b = 32;
        return a / b;
}

(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: [Select]
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

However, even with -O1 it does the optimization for us:
Code: [Select]
divide:
        pushl   %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %eax
        shrl    $5, %eax
        leave
        ret

(Quick guide to i386 assembly: "shrl" is logical shift right, "divl" is unsigned division).
« Last Edit: September 17, 2010, 01:48:47 am by andri »
 

Offline migsantiago

  • Frequent Contributor
  • **
  • Posts: 381
  • Country: 00
    • MigSantiago's Web Site
Re: C learning
« Reply #26 on: September 17, 2010, 01:54:10 am »
This is not really about knowing assembly, rather about general base-2 calculations.

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

Offline joelby

  • Frequent Contributor
  • **
  • Posts: 634
Re: C learning
« Reply #27 on: September 17, 2010, 02:08:22 am »
Yeah, I was just looking for a simple example. Sorry.  :P

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.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf