I have a question of howto do some basic math in C. This is a task that is very simple in assembly. How do you quickly determine the maximum set bit in a number in a minimal number of operations in C? I know slow ways of doing this in C by multiple testing, though not a direct way.

For example if implementing the function

**. In assembly it can be done like:**

*unsigned long log2(unsigned long n);*Code: Select all

```
;Crude log2 implementation, gives the log2 of
; the largest number below the input value that
; is a power of 2.
;ON ENTRY: R0 = Value to find the base 2 log of.
;ON EXIT: R0 = Log 2 of input value.
.log2
TST R0,&FFFFFFFF
CLZNE R0,R0
RSBNE R0,R0,#31
MOV R15,R14
```

This is very important for many operations. For example many display operations, we prefer a row pitch that is a power of 2, and obtaining the log2 of the row pitch for use in quick calculations is important (even though only needed when the display resolution is setup, if it changes the virtual FB width). For example to quickly do a setpix (assumes color is 32bpp, and color value passed in is valid):

Code: Select all

```
typedef unsigned long ULONG;
int FBSetPix32(ULONG Color, ULONG x, ULONG y)
{
if (x <= ScrMaxX && y <= ScrMaxY)
FB32[(y << ScrRowShft) + x)] = Color;
}
```

Code: Select all

```
;Set a 32BPP pixal at point (x,y) on a screen with a framebuffer that
; has a power of 2 row pitch.
.FBSetPix32
STMFD R13!,{R3-R4,R14}
LDR R3,ScrMaxX ;Sanity check, make sure we are in bounds.
CMP R1,R3
LDRHI R4,ScrMaxY
LDRLS R3,ScrRowShft ;So we can calc the row offset.
CMPHI R2,R4
LDRLS R4,FB32
ADDLS R1,R1,R2,LSL R3 ;Quick way to calculate the index.
ADDLS R1,R1,R4
STRLS R0,[R1]
LDMFD R13!,{R3-R4,R15}
```

**FB32**is ULONG pointer to the base address of the frame buffer.

**ScrMaxX**is the maximum x coord for the current screen resolution.

**ScrMaxY**is the maximum y coord for the current screen resolution.

**ScrRowShft**is the log2 of the row pitch (and assumes a power of 2 for the row pitch in this case).

Needless to say the same information is needed for all frame buffer drawing and raster functions.

There are also many other uses where finding the topmost set bit quickly would be very helpful.

*I think I corrected the typos in the code. Sorry about that, they are quick on the fly typed in examples to illustrate the point of the question.*