Results 1 to 2 of 2
  1. #1
    Aaron_Sharp is offline Member
    Join Date
    Jan 2011
    Posts
    7
    Rep Power
    0

    Default 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 10:45 AM. Reason: missing information

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,682
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Aaron_Sharp View Post
    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?
    Reread my code again; I wrote:

    Java Code:
    for (byte m = 1; m != 0; m <<= 1)
    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:
    byte b= ...;
    for (byte m= Byte.MIN_VALUE; m != 0; m>>>= 1)
       if (m <= b)
          System.out.print((b&m == 0)?0:1);
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Replies: 1
    Last Post: 04-21-2010, 03:28 AM
  2. Shift Off Trailing Zeroes
    By nwboy74 in forum New To Java
    Replies: 5
    Last Post: 02-25-2010, 08:56 AM
  3. Trimming URL
    By Juuno in forum New To Java
    Replies: 1
    Last Post: 03-10-2009, 06:17 PM
  4. How to display numbers with leading zeros
    By Java Tip in forum java.lang
    Replies: 1
    Last Post: 06-14-2008, 07:36 PM
  5. How to display numbers with leading zeros
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 10:34 PM

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
  •