how to change integer to byte value

i need to change long/integer/short number to byte value , on the other hand, convert byte value to long/integer/short.is there anyone can tell me how to do it?
[174 byte] By [a_wavea] at [2007-10-2 9:06:09]
# 1

> i need to change long/integer/short number to byte

> value , on the other hand, convert byte value to

> long/integer/short.

>

> is there anyone can tell me how to do it?

int x = 999;

byte b = (byte)x;// You need to cast explicitly since you are losing precision.

and

byte b = ...;

int x =b;// No casting needed.

aniseeda at 2007-7-16 23:13:10 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...
# 2

Converting a int to a byte requires explicit casting as

int i = 100;

byte b = (byte) i; // b = 100;

But please take care, as downcasting chops the upper bytes . int has 32 bits while byte has 8 bits. So while downcasting, the upper 3 bytes(i.e 24 bits) will be chopped.

For example,

int i = 256;

byte b = (byte) i; // b = 0; Wrong

Converting an byte to short or int, doesn't requires explicit casting. It is done by the java compiler itself.

For example,

byte b = 100;

int i = b; // No casting requried.

Thanking you.

Great_Javaa at 2007-7-16 23:13:10 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...
# 3

OK I'll byte no real pun intended though.

I am having all kinds of trouble outputing to a stream.

I have a value that is an integer 47012 and I

cast it

int foo = 47152

byte bar = (byte) foo;

System.out.println(foo); //just to see if the int is ok

// I am seeing 47152

System.out.println(bar); // in a crazed attempt to get a check of the value

// I am seeing 48

oStream.write(bar);

the file I am writing to is filled instead with

all 30. I know that 30 = 48 in hex so this makes some sense as java is converting the byte to dec 48.

what I dont get is that 47152 = B830 so since I am to collect my data and then convert it to a byte and since I am loosing the top 2 digits how to I preserve them to output to the stream?

the1bugbeara at 2007-7-16 23:13:10 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...