# hex to binary - how do i flush off the leading 0

• March 4th, 2014, 10:07 AM
kennylty
hex to binary - how do i flush off the leading 0
any idea how do i flush off the leading 0s from my results? I want to start with 1.

Code java:

import java.util.Scanner;

public class Hex2Bin {
public static void main(String[] args) {
String hexStr;
int hexStrLen;

String[] binStrs = {"0000", "0001", "0010", "0011", "0100", "0101",
"0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};

Scanner in = new Scanner(System.in);
hexStr = in.next();
hexStrLen = hexStr.length();
System.out.print("The binary equivalent is: ");

for (int pos = 0; pos <hexStrLen; ++pos){
char hexChar = hexStr.charAt(pos);

if (hexChar >= '0' && hexChar <='9') {
System.out.print(binStrs[hexChar-'0']);
}else if (hexChar >= 'a' && hexChar <='f'){
System.out.print(binStrs[hexChar-'a'+10]);
}else if (hexChar >= 'A' && hexChar <= 'F'){
System.out.print(binStrs[hexChar-'A'+10]);
}else{
return;
}
}
}
}

• March 4th, 2014, 10:46 AM
Norm
Re: hex to binary - how do i flush off the leading 0
If you have a String: "0001" you could use some String methods to find the first "1" and another String method to get the contents of the String from that location to the end of the String.
• March 4th, 2014, 11:14 AM
kennylty
Re: hex to binary - how do i flush off the leading 0
Quote:

Originally Posted by Norm
If you have a String: "0001" you could use some String methods to find the first "1" and another String method to get the contents of the String from that location to the end of the String.

I understand that i need to use String's indexOf() and substring(). But just how am i gonna insert into my code
• March 4th, 2014, 11:43 AM
Norm
Re: hex to binary - how do i flush off the leading 0
Change the code to build a String (vs printing the parts)
use those two methods to strip the leading "0"s off the String
• March 5th, 2014, 11:30 AM
gto11520
Re: hex to binary - how do i flush off the leading 0
i think there is a way to do this without a string.

look into Bitwise and Bit Shift Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

bitshifting may resolve your problem. i dont remember how my prof did in the pass
• March 5th, 2014, 06:32 PM
dicdic
Re: hex to binary - how do i flush off the leading 0
Quote:

i think there is a way to do this without a string.
I think that is only applicable numbers. How can you use Bit Shift in String?

Quote:

I understand that i need to use String's indexOf() and substring(). But just how am i gonna insert into my code
just get the indexOf() to get the first index of 1 in your string.
then use substring() to get what you want, get the string from indexOf(1) up to the original length of the string