March 02, 2024, 01:58:02 PM

News:

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.

sapero

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
{
#asm
fld1
fild dword[ebp+8]
fyl2x                  ; st0 is popped
fistp dword[ebp+8]
#endasm
return x;
}
but not all results are correct.
Manually calculating bits works better (and null is allowed!):sub log2(int x),int
{
#asm
mov eax,[ebp+8]
xor ecx,ecx
and eax,eax
jz .ok
.go:
inc ecx
shr eax,1
jnz .go
.ok:
mov [ebp+8],ecx
#endasm
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()
{
   print(inet_ntoa(GetNetMask(30)));
   return;
}

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