Julian
Julian

Reputation: 1675

How do you compare only certain bits in data type?

I'm trying to learn a bit about emulation and I'm trying to think of how I can decode opcodes. Each opcode is a short data type, 16 bits. I'd like to be able to compare only specific sets of 4 bits. For example: there are multiple opcodes that start with 00, such as 0x00E0.

I'd like to be able to compare each of these values in either bit or hexidecimal form. I was thinking maybe something along the lines of bit shifting to bump of everything else off so that the bits I don't care about would zero out. That may cause issues for the center bits and will require additional steps. What kind of solutions do you guys use for a problem like this?

Upvotes: 0

Views: 3441

Answers (3)

Alok
Alok

Reputation: 101

you can easily create the mask of "nbits" and and shift "pos" number of bits and do comparision

uint32_t mask = ~((~0) << nbits);

if( (num(mask << pos)) == 0x00e0 ) {
    /* Do something */
}

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

This is simple bit manipulation. You can mask the relevant bits with

int x = opcode & 0x00f0;

and compare the resulting value

if (x == 0x00e0) {
    /* do something */
}

Upvotes: 1

Thomas
Thomas

Reputation: 181745

Use a bit mask, which has the bits set that you care about. Then use the & operator to zero out everything that you don't care about. For instance, say we want to compare the lowest four bits in a and b:

uint16 mask = 0x000f;
if ((a & mask) == (b & mask)) {
  // lowest 4 bits are equal
}

Upvotes: 3

Related Questions