4

I have the following 4 integer values which represent ARGB:

int value1 = 0xFF;
int value2 = 68;
int value3 = 68;
int value4 = 68;

I would like to concatenate the values so they represent following:

int test = 0xFF686868;

My current approach is to use:

int test2 = 0xFF | value1 | value2 | value3;

But using this approach the integer values of test1 and test2 do not match, what am I doing wrong? I am limited to J2ME.

S-K'
  • 3,188
  • 8
  • 37
  • 50

1 Answers1

10

You're almost there: all you need to do is shifting the individual bytes into position before OR-ing them together.

int test2 = (value1 << 24) | (value2 << 16) | (value3 << 8) | value4;

Don't forget to make your 68s hex for the desired output of 0xFF686868

int value2 = 0x68; // Add 0x to all three of the 68s
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Could you explain why I must shift the bytes? Also, how would I convert 68 to 0x68? Thanks – S-K' Feb 12 '13 at 11:08
  • 2
    @S-K' Think of shifting left as adding zeros to the right. In hex notation, a shift by 4 is the same as adding one zero to the end. Shifting by 24 adds 6 zeros, by 16 - 4 zeros, by 8 - 2 zeros. Since `OR`ing with zero yields the original number, shifting and `OR`ing bytes lets you construct a four-byte number. – Sergey Kalinichenko Feb 12 '13 at 11:13