converting 4 bytes into unsigned int and back..?
i am using datagram sockets to send and recieve packets with online servers. when i do a certain command the server sends me a packet containing 4 bytes as a form of authentification. I need to then turn these 4 bytes into an unsigned integer, then convert the int back into a byte array so that i can send it out on the next UDP packet which only sends byte arrays. i have tried sending the exact bytes back but this does not work and i am told that i need to unsign the int when i send it back.
sample bytes from server :
49
48
56
55
could someone please tell me how to turn these 4 bytes into an unsigned int, and then back into a byte array to transfer them back over the UDP socket.
Thank you very much for ur time.
[778 byte] By [
gabadoo] at [2007-9-26 2:17:01]

I would suggesting and-masking the value that you get from the server to get each byte.
int serverInt = // the value that you get from the server
int mask = 0xff; // 255 - 8 bits set to 1.
byte[] bytes = new byte[4];
for(int a = 0; a < 4; a++) {
bytes[a] = (byte)serverInt&mask;
serverInt = serverInt >> 8;
}
That 'should' give you your four bytes. You might have a problem with the sign of the bytes since java doesn't have an unsigned int. If you do try this change,
bytes[a] = (byte)Math.abs(serverInt&mask)
. Hope this helps.
You might try using BigInteger. You can create a BigInteger from an array and designate that the number represented by the array is positive. BigInteger will also convert it back to an array, but you may end up with a 5 byte array, or less-than-4 byte array.
The mask is needed to clear the bits that sign extension may set during byte -> int convertion. There is no need to mask when doing int -> byte convertion.
This code converts 4 bytes to an integer:
int i=(b[0]&0xff)<<24 | (b[1]&0xff)<<16 | (b[2]&0xff)<<8 | (b[3]&0xff);
or
int i=(b[3]&0xff)<<24 | (b[2]&0xff)<<16 | (b[1]&0xff)<<8 | (b[0]&0xff);
Since Java does not have unsigned int type you can use long to hold all possible values of unsigned int:
long result=(long)i&0xffffffffl;
Dmitry Hudyakov
Brainbench MVP
ah the days of C, when you could use a union..
Or you could do this (obviously you would keep the streams around and reuse them.)
import java.io.*;
public class KillMe
{
public static void main( String[] args )
{
try
{
int myValue = 0xBAADF00D;
System.out.println("myValue = " + myValue );
ByteArrayOutputStream baos = new ByteArrayOutputStream( 4 );
DataOutputStream dos = new DataOutputStream( baos );
dos.writeInt( myValue );
byte[] b = baos.toByteArray();
System.out.println("b = " + b.toString() );
ByteArrayInputStream bais = new ByteArrayInputStream( b );
DataInputStream dis = new DataInputStream( bais );
myValue = dis.readInt();
System.out.println("myValue = " + myValue );
}
catch (Exception e)
{}
}
}
And i thought java only let you do things one way.. :)I must say the DataOutputStream guy takes the cake.