Results 1 to 3 of 3
  1. #1
    sranil is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default Sending unsigned bytes using DatagramPacket

    Hi All,

    As Java doesn't support unsigned bytes, can you please tell me how to send the unsigned byte using DatagramPacket.

    Regards,
    Anil

  2. #2
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    7

    Default

    Anil, the unsigned/signed distinction is only relevant when you're interpreting the bytes. Otherwise, a byte is just a byte. So, say you want to send the byte value 200, you just add (byte) 200 to the array of data you're sending. At the other end, to read the signed byte as though it were unsigned, just and with 0xff. So:

    Java Code:
    // sender
    byte[] dataToSend = ...
    dataToSend[0] = (byte) 200;
    and then the receiver:

    Java Code:
    byte[] receivedData = ...
    int firstByte = receivedData[0] & 0xff;
    On the receiving end, because the byte type stores -128 to 127, we put the value into an int, so that values between 128 and 255 can be represented.

    You may also be interested in my article on the Java equivalent of 'unsigned'.
    Last edited by neilcoffey; 04-21-2009 at 06:08 PM. Reason: added ref

  3. #3
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    The ByteBuffer class is also very helpful, although it doesn't address this exact issue. What it does provide is character set encode/decode and assistance putting and getting various primitives into and out of a byte[].

Similar Threads

  1. How to read first 9 bytes and write in...?
    By aRTx in forum New To Java
    Replies: 8
    Last Post: 03-26-2009, 03:54 PM
  2. reading in unsigned ints into a 2D array
    By newToIt in forum New To Java
    Replies: 9
    Last Post: 03-06-2009, 01:36 PM
  3. midi bytes
    By willemjav in forum Advanced Java
    Replies: 77
    Last Post: 07-29-2008, 04:10 PM
  4. Reading bytes from InputStream
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-25-2007, 08:51 PM
  5. how to know the number of bytes
    By gabriel in forum New To Java
    Replies: 2
    Last Post: 08-06-2007, 06:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •