# Thread: Combining multiple ints to 2 bytes.

1. Member
Join Date
May 2011
Posts
8
Rep Power
0

## 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.
Last edited by gonzalioz; 05-12-2011 at 01:31 PM. Reason: Wrong title, should be 1 byte.

2. 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

3. Member
Join Date
May 2011
Posts
8
Rep Power
0
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!

4. 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:

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

Jos

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•