Results 1 to 4 of 4
  1. #1
    gonzalioz is offline Member
    Join Date
    May 2011
    Rep Power

    Default Convert Int (last 8 bits) to Byte

    Hi all,

    I need to convert a int to a byte and I am having a really really hard time. I tried shifting operators, casting all kinds of weird stuff I found on the internet. But nothing works. Everytime my Integer gets to 128 or above and I cast it to a byte it will turn negative.

    My testing code:
    Java Code:
    int i1 = 234;		
    byte attempt1 = (byte) i1;	
    byte attempt2  = (byte) (i1 >> 8);
    byte attempt3  = (byte) ((i1 << 24) >> 24);
    System.out.println("i1: " + i1 + "  |  " + Integer.toBinaryString(i1));
    System.out.println("attempt1: " + attempt1);
    System.out.println("attempt2: " + attempt2);
    System.out.println("attempt3: " + attempt3);
    Java Code:
    i1: 234  |  11101010
    attempt1: -22
    attempt2: 0
    attempt3: -22
    Please please can somebody help me? I am pretty desperated.

    Thnx a lot in advance.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power


    A simple cast will do the job:

    Java Code:
    int i= ...;
    byte b= (byte)i;
    kind regards,

    The only person who got everything done by Friday was Robinson Crusoe.

  3. #3
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Rep Power


    Bytes will never go higher than 127. There are no unsigned variables in Java, if that's what you're after; if you want a number higher than 127, you have to either use a char (16bit) or an int (32bit).

    EDIT: There's also long, of course (64bit) but an int will generally suffice.
    Last edited by Toll; 05-13-2011 at 07:42 PM.

  4. #4
    gonzalioz is offline Member
    Join Date
    May 2011
    Rep Power


    Thanks. I was confused with .NET byte. In .NET byte is unsigned by default :).

    Thank you!

Similar Threads

  1. Converting a byte to individual bits
    By Aaron_Sharp in forum New To Java
    Replies: 18
    Last Post: 01-06-2011, 10:09 AM
  2. convert byte array to string.
    By newbiejava in forum New To Java
    Replies: 9
    Last Post: 07-30-2010, 08:00 PM
  3. How Convert a Byte array to a image format
    By perlWhite in forum Advanced Java
    Replies: 1
    Last Post: 08-22-2009, 07:05 PM
  4. convert byte[] to image
    By brijesh.baser in forum Java Servlet
    Replies: 0
    Last Post: 03-13-2009, 02:44 PM
  5. Convert Byte [] to BufferedImage
    By Smily in forum Advanced Java
    Replies: 3
    Last Post: 04-28-2008, 05:54 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