Question

Convert c code into assembly code

Asked by: tjodolf

Hey. I hope you can help me with converting some c code into assembly code, i have tried much now, and i still don't get it. What would help me alot, would be some comments for each line in the assembly code, so i better can understand to convert process...

Here is the code:

/* Standard quicksort. */
void quicksort(int a[], int left, int right)
{
      int lp = left - 1;
      int rp = right;
      int v = a[right]; /* the partioning element */

      if (right <= left)
            /* Array has one or null elements to sort */
            return;

      /* No elements to the left of lp are greater than the partioning elemnt. */
      while (1) {
            while (a[++lp] < v)
                  ;

            while (v < a[--rp])
                  /* In case the partioning element is the smallest in the array */
                  if (rp == left)
                        break;

            if (lp >= rp)
                  break;

            /* Deadlock, switch elements and continue */
            swap(&a[lp], &a[rp]);
      }
      /* This completes the partioning */
      swap(&a[lp], &a[right]);

      /* Now every element to the left of a[lp] are smaller than a[lp],
       * and every element to the right is larger. */

      quicksort(a, left, lp - 1);
      quicksort(a, lp + 1, right);
}

static void swap(int *x, int *y)
{
      int temp = *x;
      *x = *y;
      *y = temp;
}



Hope you can help.

Terje.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-09-09 at 10:26:28ID21124987
Tags

c

,

convert

,

assembly

,

code

Topic

Assembly Programming Language

Participating Experts
5
Points
125
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Assembly inline function
    i have a senario where i want to treat all my numeric values as characters but still do all the arithmetic operations on that character data which basically comprises of numbers. i also do not want to use all the conversion fuctions available in c or c++ to convert into arith...
  2. Need help on converting assembler to inline assembly
    Im sort of a newbie on this.. need help on having this code in inline assembler for Visual C++ 6.0.. ive been trying to understand why the msdev hangs when it reaches INT 21h after i some of the 16 bit registers to 32 e.g eax,ebx,edi etc.. C++ code is as follows: #include &...
  3. TypeConverter with Standard values for an Assembly
    I have created a class called AssemblyConverter that derives from TypeConverter. I want the developer to choose an assembly from a dropdown list in the property editor during design time. But when I press the triangle to see the list of possible choices I get a NullReference ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: grg99Posted on 2004-09-09 at 14:03:12ID: 12021428

A question:  Why do you want to do this?   It's hard and the benefits are few.  

 Most compiler nowdays can generate very good code, especially for this kind of simple stuff, just some if()s and calls.   In assembly you'd be doing pretty much the same thing.  There's no advantage to the usual trick of keeping values in registers (because of the recursion, you have to push/pop all of them anyway), or unrolling complex loops (there arent any), or using SIMD instructions (not much data to process in parallel here).

One sure way is to use a C compiler and capture its output (-S option IIRC).








 

by: DawafflemanPosted on 2004-09-11 at 10:28:03ID: 12035105

;  first you need to start off and declare your variables and your proccessor/model
; i use model medium because it is good for small projects and easy to work with
; ill use tasm code but it should be very easy to convert to masm (or nasm)

.model medium
.386                          ;386 instructions should be sufficient
.stack 500h                ; a good size stack for recursions might need to make this bigger
.data                         ; declair your data section (if you are using tasm, otherwise it is different)
                                ; put all of your variables here that you will use throught the program
lp          dw    ?          ;you use    (variable name)    (size)    (value)    form
rp          dw   ?          ;use question mark to set as undefined
v           dw   ?           ; you might want to use db (declare byte) here instead of dw (declare word)
right      dw   ?
left        dw     ?
x           dw    ?
y           dw    ?
temp     dw    ?
a           dw    ? dup (?)   ; this is an array with ? sets of ? (i dont know if this will work right, it  
                                     ; might be safer to put 100 dup (?) just so the assembler knows how
                                     ; many blocks there are, but you can try it either way.
;functions here-----------------------------------------------------------------------------------

quicksort proc                 ; name of procedure followed by 'proc'

                                     ;im not sure exactly how your code works so i will try my best to convert it
                                     ; in asm you dont need to pass your variables because they are all global
                                     ;(i think) so you are changing the actual value of the variable (its like
                                     ; passing it by reference) so if you dont want that to happen use separate
                                     ;variables just in your functions. heres the rest of the function:
                                     ;initializing variables here
mov ax,left                     ; form:  (move) (destination),(source)
sub ax,1                         ;form:   (sub) (destination),(source)  outcome is dest=dest-source
mov lp,ax                        ; these three steps=     lp = left - 1

mov ax,right                   ;you cant move memory to memory in assembly so it needs to go
mov rp,ax                      ;through a register first, like i did here

mov si,offset a         ;this is how you get a pointer. it points to a in memory (si is a good pointer
add si,[right*2]        ;register) now we add a + right * sizeof word (which is 2)
mov v,si                   ;si had a[right] in it and moved it to variable 'v'

if1:                         ;just to make it look better not neccissary here
mov ax,right            ;i compare using a register and a memory i think you can do mem & mem tho
cmp ax,left              ;this will set flags based on the outcome of the comparison
jle return                 ;this jumps if lessthan or equal, to return. sometimes you need jbe instead

mainloop:              ;while(1) always returns true correct? so this is an endless loop

while2:                   ;ill name the while loops to make it easier to comprehend
inc lp                      ;increase lp by 1 (++lp)
mov si,offset a
add si,[lp*2]           ;a[++lp]
cmp si,v                  ; < v
jge return                ;if a[++lp]<v we want to continue otherwise we will jump to the end  

while3:
dec rp                    ;--rp    we are on the next while loop now
mov si,offset a
add si,[rp*2]          ;a[--rp]
cmp v,si
jge while2                    ;if v>a[--rp] than skip this part here and return to while 2, otherwise do it

if2:
mov ax,rp
cmp ax,left             ;see if rp==left
je endofwhile         ;this will simulate a break statement and will jump to the end of the while
                            ;statements (i think this is how you want it)
if3:                        ;fall through to if statment number 3
mov ax,lp
cmp ax,rp             ;if ax>= rp then 'break'
jge endofwhile

mov si,offset a
add si,[lp*2]
mov x,si                ;you have to set up the variables before you call the function
mov si,offset a
add si,[rp*2]
mov y,si               ;now the proc is ready to be called because x has a[lp] and y has a[rp]
call swap              ;if all that is good we will call swap. notice to use a procedure you type
                           ; (call) (procedure name)
jmp mainloop        ;jump to main loop (while) if everything was ok
endofwhile

mov si,offset a
add si,[lp*2]
mov x,si                ;you have to set up the variables before you call the function
mov si,offset a
add si,[right*2]
call swap

                            ;when you first call quicksort you have to set the variables up in this fashion:
mov ax,left
mov left,ax            ;sets up second parameter
dec lp                   ;lp-1
mov ax,lp
mov right, ax         ;third parameter is set up now, so we can call the proc now
                            ;we dont need to set up the first parameter because that would be pointless
                            ;to set an array to an array just copy your array to the 'a' array if you have to  
call quicksort

mov ax,right
mov right,ax            ;set up 3rd parameter
inc lp                      ;lp+1
mov ax,lp
mov left,ax              ;set up and ready to go
call quicksort

endofwhile:
return:                   ;point of returning to the program
ret                         ; this pops the cs:ip off the stack to return to the caller
endp                      ;says this is end of procedure (function)

;next procedure here-----------------------------------------

swap proc

mov ax,[x]       ;move to ax whats pointed at by x
mov temp,ax    ;temp = x
mov bx,[y]
mov [x],bx       ;move y to what x is pointing to (im not sure if you need to brackets)
mov ax,temp
mov [y],ax      ;move temp to what y points at

ret
endp             ;end of swap procedure

i hope this works good for you, you might need a few minor adjustments tho. your code was a little confusing and i think you might have made a few mistakes in it, but that might be just me. i wasnt really sure where your while statments were SUPPOSED to end so i made a guess of what i thought was supposed to happen there.
if it doesnt work comment your C++ code more and tell me what the assembler errors were so i can fix it hopefully :)

one thing is for sure, this is a difficult way to do things and you should only do it if its absolutly neccissary ofr speed or otherwise.

 

by: DanRollinsPosted on 2004-09-11 at 14:42:29ID: 12036020

No ASM version of this will be any faster than optimized code generated by a C compiler.
-- Dan

 

by: CmdrRickHunterPosted on 2004-09-11 at 23:09:00ID: 12037294

and infact, C code can usually be faster, because it is easier to be complicated.  You can do tricks like  heapsorting small partitions because once the item count gets small, the algorithmic advantages of quicksort give way to the fewer, simpler, perhaps even more cache friendly heapsort functions.

You can do it in assembly too, but its that much longer, and that much more work to hand optimize.

Also, C compilers can take advantage of its knowledge of the computer.  It can see when a LEA can be used to speed up a pointer access.  It can see where a stall occurs, and often re-order things to sneak around it, all invisible to you.  A perfect example is in MIPS.  In MIPS, a branch can take quite a while, so it offers a delayed branch, where the processor executes the instruction immediatly after the branch, no matter whether or not it takes the branch.  This is usually filled in (by the compiler), with a NOP, but if it can execute the first instruciton of one branch, without affecting the outcome of the second, it will put it in there.
Handling that in assembly is a pain in the butt.

 

by: manish_regmiPosted on 2004-09-11 at 23:10:19ID: 12037300


but if you want asm anyway, use the S switch to produce assembly code.
eg,
gcc -o abc -S -O3 xyz.c (for gcc)
tcc -S xyz.c
 
IIRC you have /Ox switch in Vc++ to optimize the code.  
  -Ox in gcc.

regards manish

 

by: grg99Posted on 2004-09-12 at 05:23:29ID: 12037900

Um,  I'm a bit peevd about your accepting that particular answer.  There's not a chance the answer is particularly faster than C compiler generated code, it doesnt use any special asm-like tricks, like loop unrolling or in-line function expansion, or MMX instructions, or block move instructions.  Not to mention it's basically not correct, as you can't use global variables for a function that is recursive.  It just won't work.  The whole thing has to be redone, using stack-based variables and parameters.



 

by: DawafflemanPosted on 2004-09-12 at 11:40:18ID: 12039414

i think it was a good attempt by me do do what the author wanted. it may not be perfect but he asked for assembly code translated from C++ code and that is what i give him. if it doesnt work properly id be willing to rework it. besides he didnt want it to be neccissarily faster...

 

by: DanRollinsPosted on 2004-09-12 at 13:50:05ID: 12039877

True.  We always assume that the Asker must want speed... but another valid reason for this request would be to learn ASM and there may be other reasons.

tjodolf,
Would you care to post a comment to us?  Or do you think we are mindless automata to do your bidding?

-- Dan

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...