C - Need to compare n
lowest bits of an int for equality.
I.e. n = 4;
xxxx1001 == xxxx1001 (x is don't care)
I.e. n = 2; xxxxxx01 == xxxxxx01
Can't think of a nice way to do it without using masks, =).
C - Need to compare n
lowest bits of an int for equality.
I.e. n = 4;
xxxx1001 == xxxx1001 (x is don't care)
I.e. n = 2; xxxxxx01 == xxxxxx01
Can't think of a nice way to do it without using masks, =).
Hi,
you could use the modulo operator. For example n = 4 and you have to ints x and y:
if((x%16) == (y%16)){ ....
Hope this helps you.
Nick
Create the mask from the number of bits:
int mask = (1 << bits) - 1;
Then you use that to compare the values:
if ((a & mask) == (b & mask))
I think what need to do is xor the values and then use a mask. For example,
(a ^ b) & (( 1<<n ) - 1)
If you really don't want to use masks (not that there is anything wrong with that!), then you could use a shift-left operator:
if( a << m == b << m )
{
}
where m is the total number of bits less the number you are interested in. That is, in the example in the question, m is 4 (ie, 8 - 4).
Edit: to be clear - I have assumed the question indicated an 8 bit integer given the format used (eg, xxxx1001), but the solution is general in that it caters for any sized integer. To determine the number of bits in the integer, use 8*sizeof(type), where type may be int, short, long, etc.