# Finding the Value of a Bit

**QUESTION:** I need to find the value of a bit in a particular number. Is
there a command like the MATLAB **BitGet **command to do this in IDL?

** ANSWER:** There is now. You can download it here.

But this is quite simple to do with the AND bitwise operator. Mati Meron points out that
for bit number *n* (bit count starts
at 0, as is usual in IDL) of integer *x*, you can find the bit value like this:

bitValue = (x AND 2^n) / 2^n

Or, more generally, you can get all of the bit values in a number like this:

array= 2ULL^UL64indgen(64) bitValues = (x AND array) / array

I've put this in an IDL function, named cgBitGet for your convenience. You can use it like this:

IDL> Print, cgBitGet(128, 7) 1 IDL> Print, cgBitGet(128, 6) 0 IDL> Print, cgBitGet(255), FORMAT='(8I2)' 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

Copyright © 2006 David W. Fanning

Last Updated 14 June 2006