Results 1 to 2 of 2
- 01-06-2011, 09:44 AM #1
Member
- Join Date
- Jan 2011
- Posts
- 7
- Rep Power
- 0
Trimming trailing zeros in a byte
Dear community,
I present you with a pair of methods. The main method executes the convert method (which I learnt thanks to a member, unfortunately I forgotten his name but I thank him again for his help). The convert method basically takes an integer and delivers its bitwise representation to be stored in a byte.
public static void main(String[] args)
{
convert();
}
public static void convert()
{
int b = 0;
for (int m = 1; m != 0; m <<= 1)
{
b = 5; //b is the current int
int bit = ((b & m) != 0)? 1:0;
byte c = (byte)bit;
System.out.print(c);
}
}
The output: 101000000000000000......
How do I remove the trailing zeros?
EDIT: The output is obviously reversed... in fact 5 = ....000000101
Thank you in advance.Last edited by Aaron_Sharp; 01-06-2011 at 09:45 AM. Reason: missing information
- 01-06-2011, 11:04 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,392
- Blog Entries
- 7
- Rep Power
- 17
Reread my code again; I wrote:
If you want to print your number highest bit first you should move the mask from BYTE.MIN_VALUE to 1. If you want to skip the leading zeros you should test for them. Something like this:Java Code:for (byte m = 1; m != 0; m <<= 1)
kind regards,Java Code:byte b= ...; for (byte m= Byte.MIN_VALUE; m != 0; m>>>= 1) if (m <= b) System.out.print((b&m == 0)?0:1);
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
Streaming an image byte by byte (and similtaneosly rendering it on screen)
By ea25 in forum New To JavaReplies: 1Last Post: 04-21-2010, 02:28 AM -
Shift Off Trailing Zeroes
By nwboy74 in forum New To JavaReplies: 5Last Post: 02-25-2010, 07:56 AM -
Trimming URL
By Juuno in forum New To JavaReplies: 1Last Post: 03-10-2009, 05:17 PM -
How to display numbers with leading zeros
By Java Tip in forum java.langReplies: 1Last Post: 06-14-2008, 06:36 PM -
How to display numbers with leading zeros
By JavaBean in forum Java TipReplies: 0Last Post: 10-04-2007, 09:34 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks