June 14, 2024, 03:50:23 AM


Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........

binary logarithm

Started by sapero, April 27, 2006, 01:31:36 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.


sometimes we need to calculate how many bits are required to store a integer i.e. while calculating network mask for given computers count.

We can use assembler command FYL2X for numbers 1-255 sub log2_asm(int x),int
fild dword[ebp+8]
fyl2x                  ; st0 is popped
fistp dword[ebp+8]
return x;
but not all results are correct.
Manually calculating bits works better (and null is allowed!):sub log2(int x),int
mov eax,[ebp+8]
xor ecx,ecx
and eax,eax
jz .ok
inc ecx
shr eax,1
jnz .go
mov [ebp+8],ecx
return x;

for 1 it returns 1, for 2 - 2, for 255 - 8

sample usage - calculate ip-mask for 30 computers
#use "ws2_32.lib"
extern int htonl(int ip); // swap byte order
extern string inet_ntoa(int ip);
global sub main()

sub GetNetMask(int nComputersCount),int
return htonl((0xFFFFFFFF - ((2^log2(nComputersCount))-1)));