hey, basically I have an assignemnet to write a C and MIPS code to determine if a number is a power of 2 or not.(that is only a beginning part to the main core of this assignment which needs this code to be used later). I'm capable of doing the C as I have studied that in engineering for three years so that part I found quite simple. the Problem is I have to take this course as a substitute, that specialises in MIPS because our C course has been closed down for good. Only thing is its a third year MIPS course so I have to play catch up with every one else in the class, and frankly Im finding it very tough.

This is the question:

"Write both, C code and MIPS assembly language procedure that will determine if a number is a power of 2 or not. Hint:For MIPS assembly language it may be helpful to write the procedure in Java first."

I'm kind of grateful that a hint was provided and I am aware that Java is somewhat similar to C but again I have never studied that so its not really any use to me. This is the C code I wrote:

bool isPowerOfTwo( unsigned int num )
{
   for ( int i = 0 ; i < 32 ; i++ )
     {
        unsigned int mask = 1 << i ;
        if ( num == mask )
           return true ;
     }
   return false ;
}

I have no clue how to actually write something similar in MIPS. any help??

Forget Java. If you can do it in C you can do it in MIPS.

Remember, a power of two is a number that has only one bit set (all the rest are zeroes), and that bit cannot be bit 0 (the least-significant bit).

Your C solution looks fine. In MIPS, you can use the sll instruction so shift left.

I like the Wikipeda: MIPS Assembly Language reference. There are good links at the bottom for learning more.

A simple MIPS program looks like:

.data
hello: .asciiz "Hello world!"

.text
main:
	# print "Hello world!"
	la	$a0,	hello
	li	$2,	4
	syscall

	# terminate
	li	$2,	10
	syscall

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.