Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Encoding Integers Into an Existing Byte Array

Status
Not open for further replies.

mesagreg

Programmer
Mar 3, 2001
53
US
I am trying to write a method that takes a byte array as an input, appends a 3-byte header onto the array and sends the resulting byte array to a remote host via an OutputStream.

My method signature is something like this:

public void write(byte[] data)
{
byte [] packet = new byte[data.length + 3];
packet = System.arraycopy(data,0,header,header.length)
packet[0] = 3; //<--- I just need to encode the integer 3
packet[1] = 0;
packet[2] = packet.length;<---I need to encode the
length of the packet here
}
My problem is that I don't know how to encode the integer values into the bytes. And I'm not sure if the arraycopy will work correctly.

Can anyone advise me on this?
Thanks,


Gregory A. Lusk, P.E., CCNA
 
There are a few approaches:

[1] cast your integers to bytes, for example:
Code:
    packet[2] = (byte)packet.length;
[2] use a ByteArrayOutputSteam, for example:
Code:
    import java.io.ByteArrayOutputStream;
    byte[] data = { 1,2,3,4,5 };
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(3);
    out.write(0);
    out.write((byte)(data.length+3));
    out.write(data, 0, data.length);
    data = out.toByteArray();
    for(int i = 0; i < data.length ; i++)
      System.out.println(data[i]);
[3] use a DataOutputStream, for example:
Code:
    import java.io.FileOutputStream;
    import java.io.DataOutputStream;

    byte[] data = { 1,2,3,4,5 };
    try {
      DataOutputStream out = new DataOutputStream(
        new FileOutputStream(&quot;data&quot;));
      out.write(3);
      out.write(0);
      out.write((byte)(data.length+3));
      for(int i = 0; i < data.length ; i++)
        out.write(data[i]);
      out.flush();
      out.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
[4] In Java 1.4, you can use the new packages java.nio, and java.nio.channels. See:
Hope this helps. Cheers, Neil :)
 
Toolkit,

Thanks so much for your post. I am fairly new to Java, coming over from the .NET world. I know how to accomplish the task using VB or C#, but didn't know how to do it in Java.

Thanks,
Gregory A. Lusk, P.E., CCNA
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top