Combining multiple ints to 2 bytes.

• 05-12-2011, 01:28 PM
gonzalioz
Combining multiple ints to 2 bytes.
Hi all,

I am trying to convert multiple ints to their binary values and that into a byte.

int version = 2; // (max 3) binary: 10
int padding = 0; // (max 1) binary: 0
int extension = 0; // (max 1) binary: 0
int cc = 7; // (max 15) binary: 0111

Together these ints would be: 1000 0111 And I want to convert that to a byte.
I have no clue how to do this.

I hope someone can help me, thanks in advance.

edit: I said 2 bytes in the title sorry... Should be 1 byte of course.
• 05-12-2011, 02:12 PM
JosAH
Quote:

Originally Posted by gonzalioz
Hi all,

I am trying to convert multiple ints to their binary values and that into a byte.

int version = 2; // (max 3) binary: 10
int padding = 0; // (max 1) binary: 0
int extension = 0; // (max 1) binary: 0
int cc = 7; // (max 15) binary: 0111

Together these ints would be: 1000 0111 And I want to convert that to a byte.
I have no clue how to do this.

I hope someone can help me, thanks in advance.

edit: I said 2 bytes in the title sorry... Should be 1 byte of course.

Have a look at the bit shift left operator << and the inclusive or operator |

kind regards,

Jos
• 05-12-2011, 03:04 PM
gonzalioz
Ah thank you very much! I got a lot further:

int val = version << 6 | padding << 5 | extension << 4 | cc << 0;
System.out.println(Integer.toBinaryString(val));

It now prints the correct binary string. But the result is still an integer. Can you help me to convert val to a byte or convert the binary string to a byte? I couldn't find a java method that is something like Convert.toByte(val) like in .net.

Thanks!
• 05-12-2011, 03:12 PM
JosAH
Quote:

Originally Posted by gonzalioz
Ah thank you very much! I got a lot further:

int val = version << 6 | padding << 5 | extension << 4 | cc << 0;
System.out.println(Integer.toBinaryString(val));

It now prints the correct binary string. But the result is still an integer. Can you help me to convert val to a byte or convert the binary string to a byte? I couldn't find a java method that is something like Convert.toByte(val) like in .net.

Thanks!

Use a type cast like this:

Code:

`byte val= (byte)(version << 6 | padding << 5 | extension << 4 | cc << 0);`
kind regards,

Jos