Results 1 to 4 of 4
- 05-13-2011, 06:34 PM #1
Member
- Join Date
- May 2011
- Posts
- 7
- Rep Power
- 0
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:
output: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);
Please please can somebody help me? I am pretty desperated.Java Code:i1: 234 | 11101010 attempt1: -22 attempt2: 0 attempt3: -22
Thnx a lot in advance.
- 05-13-2011, 06:45 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,375
- Blog Entries
- 7
- Rep Power
- 17
A simple cast will do the job:
kind regards,Java Code:int i= ...; byte b= (byte)i;
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 05-13-2011, 07:38 PM #3
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.
- 05-13-2011, 08:38 PM #4
Member
- Join Date
- May 2011
- Posts
- 7
- Rep Power
- 0
Similar Threads
-
Converting a byte to individual bits
By Aaron_Sharp in forum New To JavaReplies: 18Last Post: 01-06-2011, 09:09 AM -
convert byte array to string.
By newbiejava in forum New To JavaReplies: 9Last Post: 07-30-2010, 08:00 PM -
How Convert a Byte array to a image format
By perlWhite in forum Advanced JavaReplies: 1Last Post: 08-22-2009, 07:05 PM -
convert byte[] to image
By brijesh.baser in forum Java ServletReplies: 0Last Post: 03-13-2009, 01:44 PM -
Convert Byte [] to BufferedImage
By Smily in forum Advanced JavaReplies: 3Last Post: 04-28-2008, 05:54 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks