Nick Heiner
Nick Heiner

Reputation: 122620

Bitwise devision? (Changing formats of ints)

I'm using Java. I have an integer where:

Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue.

I would like to change this to an int where:

Bits 5-7 are red, 2-4 are green, and 0-1 are blue.

I'm not sure how best to go about this. (Obviously, some fidelity in representable colors will be lost. This is acceptable, as long as it's proportionate, so the colors look roughly the same.)

Can I just divide?

Upvotes: 2

Views: 161

Answers (3)

Alnitak
Alnitak

Reputation: 340055

For each component, shift bits and mask out the least significant bits.

In long hand, if col is your original colour then:

r = (col >> 21) & 0x07; // bits 21 - 23
g = (col >> 13) & 0x07; // bits 13 - 15
b = (col >>  6) & 0x03; // bits  6 -  7

and your new value is:

(r << 5) | (g << 2) | b

Or, to roll it all into one expression:

rgb = (col & 0xe00000) >> 16 | (col & 0xe000) >> 11 | (col & 0xc0) >> 6; 

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

I suggest you

int argb =
// extract the colours. 
int red = (argb >> 16) & 0xFF;
int green = (argb >> 8) & 0xFF;
int blue = argb & 0xFF;

// reduce the number of bits.
red >>= 5;
green >>= 5;
blue >>= 6;

// build the new value
int rgb2 = (red << 5) + (green << 2) + blue;

Upvotes: 3

MeBigFatGuy
MeBigFatGuy

Reputation: 28608

no. you need to do bitshifting and masking.

For instance, to get red, you want 3 bits. So you need to grab the most significant bits of red which are bits 23, 22, and 21.

so

int red = ((color >> 21) & 0x07); // gets the top 3 bits of the src red, and put in bottom of int
int newColor = red << 4; // shift back up to the new color

you'd have to do that for each component, and or (|) the values into the new color

Upvotes: 1

Related Questions