BitShifting problem

I have a file which contains indexes to tiles.

1
2
3
4
struct MegaTile
{
	unsigned short images[16];
};


There is a copy of this structure for every tile. The first bit is a flag which tells if the tile is flipped or not and the rest of the bits are the index.

So I do this
1
2
3
4
5
for(mit = 0; mit < 16; mit ++)
{
     index = megatile.images[mit]/2;
     flip = megatile.images[mit] >> 15;
}

But this produces wrong results. I also tried ((megatile.images[mit]<<15)>>15)
but still isn't working. Any idea why this isn't working. The tiles are stored correctly in the file.
flip = megatile.images[mit] << 15;
shifting 15 bits to the left should give you first bit (other bits will be unset)

cos bits are stored from left to the right like this:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 /*here are 16 bits only cos short has 2 bytes = 16 bits*/
here your flip bit is bit 0
so shifing 15 bit to the left will erease all bits except bit 0

folowing this, to get index you'll shift them 1 bit to the right:
index = megatile.images[mit] >> 1


or you can use biwise & (bit_or) like this:
1
2
index = megatile.images[mit] & 0x177776
flip = megatile.images[mit] & 0x1

that will filter bits trough hex mask to get particular bits
Last edited on
Yes thank you very much codekiddy. flip = megatile.images[mit] << 15; worked perfectly. I got the wrong order of the bits. I though the order of the bits was 0 1 2 .... 15 Silly me :D
Ok so the bits order is from left to right starting from the last bit heading to the first
For example unsigned short int - 16bits
15 14 13 ... 1

So how is the number stored? For example the number 7 - 0111
0000 0000 0111 Is that correct?
Number 4 0001 is
0000 0000 0001

The if I have the following
usigned short num = FFEE EEED DDDC BAAA

How would I get which number the AAA represent and which the DDD
I tried
unsigned short AAA = (num << 13) >> 13;
unsigned short DDD = (num << 6) >> 13;

Is that correct? I'm confused about the bits even though I read about it on wikipedia and have studied it in university :S
1
2
3
4
5
a = num /*>> 0*/ & 7 /*2^3 - 1*/;
b = (num >> 3) & 1 /*2^1 - 1*/;
c = (num >> 4) & 1 /*2^1 - 1*/;
d = (num >> 5) & 15 /*2^4 - 1*/;
...
01011001 <-- stored bits
00110000 <-- mask to get bit 4 an 5:
---01------- <--will produce this

to setup this mask use & operator

for example:
01011001 & 00110000 = 01

this tels you that number 1 is stored at bit 5 and 6;

this means this:

49 & 48 = 1
0x59 & 0x30 = 0x1

I recommed you to use "programers calculator" to calculate mask,
which also enables you to easly manipulate bits and convert hex to oct to dec

if u use windows just type calc into search
or use KCalc in linux
Last edited on
Topic archived. No new replies allowed.