Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > pl.comp.programming > #28121

z uczty - jak znaleźć maskę najstarszego bitu?

From Borneq <borneq@antyspam.hidden.pl>
Newsgroups pl.comp.programming
Subject z uczty - jak znaleźć maskę najstarszego bitu?
Date 2015-12-03 08:10 +0100
Organization ATMAN - ATM S.A.
Message-ID <n3opsf$6ep$1@node1.news.atman.pl> (permalink)

Show all headers | View raw


W książce "Uczta programistów" było wyszukiwanie numeru najstarszego 
zapalonego bajtu dla 32 bitowych liczb:

///return the most significant bit which is set, the same as BSR 
assembler opcode
///but assembler is not portable
int find_set_bit(unsigned int x)
{
int n;
   if (x==0) return 0;
   n = 0;
   if (x<= 0x0000ffff) { n = n+16; x = x << 16; }
   if (x<= 0x00ffffff) { n = n+8; x = x << 8; }
   if (x<= 0x0fffffff) { n = n+4; x = x << 4; }
   if (x<= 0x3fffffff) { n = n+2; x = x << 2; }
   if (x<= 0x7fffffff) { n = n+1; }
   return 31-n;
}


Mam funkcję sprawdzającą czy jest tylko jeden zapalony bit dla dowolnego 
typu:
/**
   return true if is only 1 or 0 set bits
   (for 0 retuns true)
   if is severeal set bits return false
*/
#define isAlone(x) ((x & (x - 1))==0)

Porównywanie z zerem potrzebne jest tylko dla tego aby z wyniku równego 
zero lub różnego od zera dawał poprawny boolean 0 lub 1

Jeśli obchodzi nas nie numer ale maska, mamy łatwiej:
/**
   return the least significant bit in x which is set
   not bit number, rather low bit mask	
*/
#define lowbit(x) ((x) & (~(x) + 1))

A teraz pytanie: czy jest jakaś funkcja analogiczna highbit(x), która 
była by równie krótka co lowbit a różniła by się od find_set_bit tym, że 
dawała by nie numer ale od razu maskę?

Back to pl.comp.programming | Previous | NextNext in thread | Find similar | Unroll thread


Thread

z uczty - jak znaleźć maskę najstarszego bitu? Borneq <borneq@antyspam.hidden.pl> - 2015-12-03 08:10 +0100
  Re: z uczty - jak znaleźć maskę najstarszego bitu? platformowe głupki <NOSPAMtestowanije@go2.pl> - 2015-12-03 18:58 +0100

csiph-web