how to convert a string value to binary?
I have some trouble in converting a string to a binary value......example:
i have a string "03 25"
how to convert it to a binary result which suppose to become or output as "0000 0011 0010 0101"
thanks
[219 byte] By [
kamenee] at [2007-11-11 10:03:36]

# 1 Re: how to convert a string value to binary?
I have some trouble in converting a string to a binary value......example:
i have a string "03 25"
how to convert it to a binary result which suppose to become or output as "0000 0011 0010 0101"
thanks
Here's how:
public class Test {
public static void main(String[] args) {
System.out.println(convert("03 25"));
}
private static String convert(String s) {
s = s.replaceAll("[^0-9]", "");
String c = "";
for(int i = 0; i < s.length(); c += format(Integer.toBinaryString(s.charAt(i)-'0'), 4), i++);
return c;
}
private static String format(String s, int l) {
while(s.length() < l) s = "0"+s;
return s+" ";
}
}
# 2 Re: how to convert a string value to binary?
Thanks for the example.But how if the string contains a char such as :
String s= "e3 25".How can i convert it to binary result which suppose to become "1110 0011 0010 0101".Anyway, i have tried to this code:
public class Test1 {
public static void main(String[] args) {
System.out.println(convert("e325"));
}
private static String convert(String s) {
String c="";
int z =0;
z = Integer.valueOf(s,16).intValue();
c = Integer.toBinaryString(z);
return c;
}
}
it is working fine .........where it is able to output as this:"1110001100100101".But when i try to convert a string which start with zero,example "0325",the output is "1100100101",where i cant print out the front zero.How to fix this problem?
Thanks.
# 3 Re: how to convert a string value to binary?
public class Test {
public static void main(String[] args) {
System.out.println(convert("e3 25"));
}
private static String convert(String s) {
s = s.replaceAll("\\W", "").toLowerCase();
String c = "";
for(int i = 0; i < s.length(); i++) {
c += format(Integer.toBinaryString(
Character.isLetter(s.charAt(i)) ? s.charAt(i)-'a'+10 : s.charAt(i)-'0'), 4);
}
return c;
}
private static String format(String s, int l) {
while(s.length() < l) s = "0"+s;
return s+" ";
}
}
# 4 Re: how to convert a string value to binary?
Thanks a lot !! It really help me to solve my problem.By the way, i dont understand how this part (s.charAt(i)) ? s.charAt(i)-'a'+10 : s.charAt(i)-'0') work.Can you explain to me?
Thanks.
# 5 Re: how to convert a string value to binary?
Im not quite sure but I think that the way it works is as follows :
boolean expression ? choice a : choice b
Now, whether the expression evaluates to true choice a is used else choice b is used.
# 6 Re: how to convert a string value to binary?
yup ... it is an "inline if/else clause": evaluates a condition just as an if/else structure does - if true, then the "?" conditional executes, if false, the ":" conditional executes.
nspils at 2007-11-11 22:37:11 >
