Code archives/Algorithms/Bit Fiddling

This code has been declared by its author to be Public Domain code.

Download source code

Bit Fiddling by Shortwind2010
Short commands to SetBit, ClearBit, ToggleBit, and ReadBit of a Integer. Easily adapted to Byte or Long.
'x=the Int with the value, bit is the bit to set, ie. 0-31

Function SetBit:Int(x:Int, bit:Int)
 	Return x | (1 Shl bit)
End Function

Function ClearBit:Int(x:Int, bit:Int)
	Return x & ~(1 Shl bit)
End Function

Function ToggleBit:Int(x:Int, bit:Int)
	Return x ~ (1 Shl bit)
End Function

Function ReadBit:Int(x:Int, bit:Int) 'This function returns 0 or 1...
	If (x & (1 Shl bit)) Return 1
	Return 0 
End Function

Comments

Shortwind2010
Why are these simple commands not part of the standard language? They could easily be overloaded in that respect if they were.


TaskMaster2010
Maybe because they are so simple?


Shortwind2010
Ha ha. Good one Taskmaster. Even though I see this come up all the time, in all languages, not just here. Seriously, I was wondering why this isn't part of a standard language, there are endless uses for functions of this type, and to be able to overload them would be very useful. (Or does the standard C library, for example, have these functions???)


Charrua2010
hi, bit manipulation are a must in a microcontroller isa (instruction set architecture) but, normally not implemented in microprocesors:they are word based not bit based. Bit manipulation aren't needed in the day by day, using high level languajes. But soner or later this kind of function are needed. Flags are everywhere and Boolean variables only need a bit, not the double word any high level lenguaje use.

Juan


SebHoll2010
This can be optimized like so:
Function ReadBit:Int(x:Int, bit:Int) 'This function returns 0 or 1...
	Return (x Shr bit) & 1
End Function



Code Archives Forum