.oO  |  List directory  |  History  |  Similar  |  Print version
Projects 
   ScummC 
   php edna 
   nixshare 
   concede 
   Orewar 
   AEval 
Portable Coding 
   Shell scripts 
   Standard C 
Random stuff 
   Slackware and UTF-8 
   Bit tricks 
Wiki 
   Links 
   Playground 
   Impressum 

Random stuff > Bit tricks

 
rw-rw-r--   albeu   wheel
Table of contents:

Bit tricks

A few bit trick for integer arithmetic, some are obvious but they are there because they are used as base for more complex stuff. Integers are assumed to be 32 bits, so you need to adujst some things for other sizes.

I got most of this stuff from The Multimedia Guru: http://guru.multimedia.cx

Normalize to 0/1

  r = !!a
  r = a != 0

0/1 to mask

  r = -a

0/1 to inverted mask

  r = a-1

Conditional bitwise not

  r = a ^ mask

Conditional negate

  r = (a+mask) ^ mask

Conditional add/sub

  r += a & mask

Conditional assign

  r = ((a ^ b) & mask) ^ b

Absolute value

  s = a >> 31
  r = (a+s) ^ s

Modulo with unsigned power of 2

  r = a & (b-1)

Modulo with signed power of 2

  s = a>>31
  r = ((((a+s) ^ s) & (b-1)) + s) ^ s

Average without overflow

  r = (a & b) + ((a ^ b) >> 1)

Is an unsigned a power of 2

  r = (a & (a-1)) == 0


Reference http://alban.dotsec.net/RandomStuff/BitTricks

Comments: 0 New comment

Prev. Slackware and UTF-8