INT to BYTE

V

Varun Gupta

How can we convert a primitive java int to Java byte.
byte and not byte[].

Waiting for replies.
 
J

Jan =?ISO-8859-1?Q?Thom=E4?=

int myInt = 65;

byte myByte = (byte) (myInt & 0xFF);

Greetings,
Jan

Varun Gupta wrote:

How can we convert a primitive java int to Java byte.
byte and not byte[].

Waiting for replies.
 
R

rxreyn3

Hmm, thought I did the same thing using the codec lib. Of course, my
brain is %90 malted hops and bong resin; so thanks for correcting me.

- Ryan
 
S

sgoo

A simple cast is all that's required, as already posted, but the '&
0xff' is not required. The cast does that already.

It *is* required if you want the output be between 0 and 255.
 
C

Chris Uppal

sgoo said:
It *is* required if you want the output be between 0 and 255.

Depends on whether you want to mask an integer value down to a byte value, i.e.
a value between 0 and 255 inclusive; or whether you want to put the resulting
value into a Java byte variable (or array slot) which holds values in the
range -128 to +127 inclusive. In the former case you should mask with 0xFF
(but don't cast, leave the result as an int); in the later case you just cast
(masking will gain exactly nothing).

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,270
Messages
2,571,102
Members
48,773
Latest member
Kaybee

Latest Threads

Top