Results 1 to 2 of 2
  1. #1
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Oregon, USA
    Rep Power

    Default [SOLVED] Byte value comes out negative

    I'm having some trouble with getting an IP address to come out in all positive numbers. Here is the code I'm using:

    Java Code:
    // host and port are given by the user
    Socket socket = new Socket(host, port);
    byte[] ipAddr = socket.getInetAddress().getAddress();
    String hostAddr = ipAddr[0] + "." + ipAddr[1] + "." + ipAddr[2] + "." + ipAddr[3];
    String hostDir = "data/" + hostAddr;

    The socket object made a connection without a problem. But other parts of the program are failing because if any of the 4 pieces of the IP addresses (also known as "octets") are over 127, then the number comes out negative because apparently a 'byte' in Java is signed.

    I have tried converting the number to an 'int' value in an attempt to make it seem unsigned, but it still came out negative.

    Java Code:
    // these didn't work

    Any help on converting a negative byte to the corresponding positive number is appreciated.

    EDIT: Convert an UNSIGNED byte to a JAVA integer - Real's Java How-to
    Last edited by Bluefox815; 07-03-2010 at 02:59 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Eastern Florida
    Rep Power


    The trick is to AND the int that came from the byte with 0xFF to strip off all the sign bits.
    Try this:
    Integer.valueOf(ipAddr[0] & 0xFF);

Similar Threads

  1. Replies: 1
    Last Post: 04-21-2010, 03:28 AM
  2. string to negative int problem
    By pendulum101 in forum New To Java
    Replies: 5
    Last Post: 11-01-2009, 06:47 PM
  3. I don't want negative money [BUG]
    By anthonym2121 in forum New To Java
    Replies: 1
    Last Post: 04-07-2009, 09:06 AM
  4. Negative elements
    By in forum New To Java
    Replies: 6
    Last Post: 12-15-2008, 05:48 AM
  5. [SOLVED] Array of first negative number
    By random0munky in forum New To Java
    Replies: 9
    Last Post: 12-09-2008, 12:17 AM

Tags for this Thread

Posting Permissions

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