Server Help

Bot Questions - Convert between types in Java

Anonymous - Mon Jan 20, 2003 2:43 am
Post subject: Convert between types in Java
If you want to make a Java bot check this out: http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html

I'm having problems with DatagramPacket, since everything is done in bytes, how can I convert an int to 4 bytes in an array? (Assuming it's an UInt32, which I don't know because Java doc's aren't too helpful). Also conversion of Strings and byte arrays back to ints or Strings. If this was C I would probably be using a struct here, but I don't think Java has any.

Having to do this for every packet is going to get annoying and hard to read:
Code: Show/Hide

    buf = new byte[8];
    buf[0] = 0x00; //Core packet
    buf[1] = 0x01; //Type
    buf[2] = 0x00; //Ticks, System.currentTimeMillis()
    buf[3] = 0x00;
    buf[4] = 0x00;
    buf[5] = 0x01;
    buf[6] = 0x00; //Version
    buf[7] = 0x01;

Dr Brain - Mon Jan 20, 2003 8:32 am
Post subject: Re: Convert between types in Java
Smong wrote:
I would probably be using a struct here, but I don't think Java has any.


A struct is just a class with no functions. Java CAN do this, just can't call it a struct.

Code: Show/Hide

public class myStruct
{
    public int myInt;
    public String myString = "Hello!";
}

Dr Brain - Mon Jan 20, 2003 8:45 am
Post subject: Re: Convert between types in Java
Smong wrote:
how can I convert an int to 4 bytes in an array? (Assuming it's an UInt32, which I don't know because Java doc's aren't too helpful).


Code: Show/Hide

int myInt = (0x6 << 24) + (0xB << 16) + (0xD << 8) + (0xF);
byte[] myBytes = new byte[4];
byte[3] = (byte)((myInt >> 24) & 0xF);
byte[2] = (byte)((myInt >> 16) & 0xF);
byte[1] = (byte)((myInt >> 8) & 0xF);
byte[0] = (byte)((myInt) & 0xF);

Smong - Tue Jan 21, 2003 2:31 pm
Post subject:
Thanks. Here is some code that works on bytes (the above code only seemed to work on 4 bits of 8 bit bytes).
Code: Show/Hide

  public final static long getLong(byte[] msg, int pos) {
    return (long)(
      ((msg[pos+3] & 0xFF) << 24) +
      ((msg[pos+2] & 0xFF) << 16) +
      ((msg[pos+1] & 0xFF) <<  8) +
       (msg[pos  ] & 0xFF)          );
  }

  public final static void setLong(byte[] msg, int pos, long val) {
    msg[pos+3] = (byte)(val >> 24);
    msg[pos+2] = (byte)(val >> 16);
    msg[pos+1] = (byte)(val >>  8);
    msg[pos  ] = (byte)(val      );
  }

Dr Brain - Tue Jan 21, 2003 4:12 pm
Post subject:
Right, sorry, didn't test it.
All times are -5 GMT
View topic
Powered by phpBB 2.0 .0.11 © 2001 phpBB Group