1. ## Bit operations?

Hello, I have the following variable:
Code:
`short opCode = 0x22a2;`
I would like to shift the order of the digits so that I get 0xa222.
I would also like to separate each individual hex digit and I thought that some bit operations could do both of these operations but I don't know how exactly.

Any help would be appreciated

2. The intended behavior is called "Circular Shift".

The hexadecimal representation will help you a lot: every digit in base16 corresponds to 4 contiguous digits in base2.

For the circular shift, you need to get the first 4 bits (i.e. the first hexadecimal digit), shift the number by 4 bits to the left, and add the first digit obtained previously.

To get the first four bits, use a bitmask: m = 0xF000 is four 1s, followed by all zeros. Hence, to isolate the first four bits, use fd=m&opCode. Now shift opCode to the left by 4 and fd to the right by 12. Then add m and opCode (or do a bitwise-or, since the last four bits of opCode are now zeros anyway).

Greets,
Philip

EDIT: make sure that a short is indeed only 2 bytes long, otherwise use a bitmask to set everything "left of the second byte" to zero explicitly.
EDIT: oops, I just realized that you want to swap bytes, not digits. My suggestions still apply, use m=0xFF00 and shift opCode and fd both by 8 (or apply the procedure above two times)

Unfortunately I'm having some tough luck extracting the digits:
Code:
```	part = mask&opCode;
opCode <<= 4;
part >>= 12;
printf("%x\n", part); // This outputs the first digit as expected

opCode <<= 4;
part >>= 12;
printf("%x\n", part); // This also works

opCode <<= 4;
part >>= 12;
printf("%x\n", part); // This outputs fffffffa instead of just a :/

opCode <<= 4;
part >>= 12;
printf("%x\n", part); // This works normally```
Am I doing something wrong?

Ivan

EDIT:
I've checked, short is indeed 2 bytes long.

4. Make your variables unsigned. Shifting signed values causes the data shifted into the most significant bit to be a copy of the one there previously so the sign of the number is maintained. In your case, you want 0s to be shifted in regardless of the MSB.

Alternatively, shift first and then mask off the least significant nibble (i.e. change mask to 0x000F). This is probably better anyway, since you can do

Code:
```for (i = 0; i < nibbleCount; i++)
{
printf("%x", opCode & 0x000F);
opCode >>= 4;
}```
Edit - never mind, that code prints things out in reverse order. Still, you get the idea.

5. If I understand you correctly you would like to do something like this(?):
Code:
```#include <stdio.h>
#include <assert.h>

int
main (int argc, char **argv)
{
unsigned short op_code, tmp;

assert (sizeof (unsigned short) == 2);

tmp = op_code = 0x22a2;

do {
printf ("  %x\n", tmp & 0xF);
} while ((tmp >>= 4) != 0);

printf ("\nbefore flip: 0x%x\n", op_code);

op_code = ((0x00FF & op_code)<<8) | ((0xFF00 & op_code)>>8);

printf (" after flip: 0x%x\n", op_code);

return 0;
}```

6. It works now.
Many thanks to all!