# Thread: Trimming trailing zeros in a byte

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

Last edited by Aaron_Sharp; 01-06-2011 at 10:45 AM. Reason: missing information

2. Originally Posted by Aaron_Sharp
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