byte to int to byte

Hi,

Here is my problem :

public class test {

public static void main(String[] args) {

int val = 169, val2 ;

byte test = (byte) val ;

val2 = test ;

System.out.println("Value of "+val+" is "+val2) ;

}

}

prints:

Value of 169 is -87

I found this solution:

public class test {

public static void main(String[] args) {

int val = 169, val2 ;

byte test = (byte) val ;

val2 = 0xff & test ;

System.out.println("Value of "+val+" is "+val2) ;

}

}

that prints:

Value of 169 is 169.

Is there a better way to do this ?

My prgram should send datas (int, double, etc...) over the network, so they are converted into byte arrays. When I want to get my datas back, I have some problems du to this int -> byte -> int conversion. Does any one have a better solution ?

[909 byte] By [dams@boulot] at [2007-9-30 19:51:11]
# 1

I'm not sure you have a problem. Have you tried sending bytes across the network and seen a problem?

The binary digits that make up 169 are 1010 1001. As an int, there are 3 bytes of leading zeros. As a byte, System.out.println shows -87 for that bit pattern. That because in converting to an int from a byte, the sign of the byte is extended. So you end up with 3 bytes of ones where you started with zeros. A lot depends on how you are converting ints to bytes and bytes to ints. In the code you posted, the way you did the conversion is probably the best because you are taking a single int, converting to a byte, and converting the byte to an int.

I have never used a ByteBuffer, but this class is targeted towards what you appear to be doing across a network. Or perhaps DataOutputStream/DataInputStream.

atmguy at 2007-7-7 0:38:40 > top of Java-index,Administration Tools,Sun Connection...
# 2

Do you mean a better way to do int / unsigned byte conversion? bytevalue & 0xff is pretty much the usual way to do it.

It could be more newbie-readable, but think of knowing that little trick as job security. There are precious few of such low-level tricks in Java; it was much better in the C days (sigh). If it seems too unreadable, put it into a static function with a nice name; the JIT compiler will hopefully inline it so there won't be a performance penalty.

sjasja at 2007-7-7 0:38:40 > top of Java-index,Administration Tools,Sun Connection...
# 3
Thanks for the "static function" tip. I'm afraid that I will forget to write some 0xFF in the code... I hope that with this inline converter, I'll do less omission.
dams@boulot at 2007-7-7 0:38:40 > top of Java-index,Administration Tools,Sun Connection...
# 4
You should use DataOutputStream/DataInputStream.Why bother rewriting primitve to bytes conversion code when you already have it?
kunda.yaniv at 2007-7-7 0:38:40 > top of Java-index,Administration Tools,Sun Connection...
# 5
I think that this may help int c = 15;Integer k = new Integer(c);byte l = k.byteValue();regards,Sachin
sachin_powale at 2007-7-7 0:38:40 > top of Java-index,Administration Tools,Sun Connection...