Bit manipulation

  • Thread starter Thread starter jfbaro
  • Start date Start date
J

jfbaro

Hi!

We would like to see if C# (1.1) has any API to manipulate bit in that
way:

For example,
send a variable to it, like a INT64 and ask that function is such bit
is 1 or 0;

like...

Int64 test = 255;

bool bit = CheckBit(test, 5);

and that CheckBit would return if the 5th bit is 1 or 0...

We know how to write that function, and it's simple, but we always
prefer to use the standard API, and we don't know if C# 1.1 has that
already.

Thanks in advance
 
As far as I know there is no real .NET equivalent of what you are
looking for, so you probably won't be able to do it with a single
function call, but it wouldn't be overly complicated to implement
yourself.
You could use
"bool bit = Convert.ToString(test,2)[4] == '1'"
to achieve the desired result.
Otherwise you could create a bitmask and XOR it with the passed
variable (probably the fastest way, if performance matters).

Sincerely,
Kevin Wienhold
 
But it starts to get a lot scrappier (plus more cycles) than just
using bitwise arithmetic... and you may want to watch out for endian
issues relating to BitConverter...

For tthe 64-bit case (in fact, most cases), you'd be better off with a
quick "shift, and, equals" test... the CPU is generally pretty
optimised for such operations. To refute my own suggestion, even
BitVector32 adds a few hurdles in terms of dealing with masks instead
of a clean bit index.

Marc
 
Back
Top