|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
please, Help me to convert String to Binary
Hi every one,
I am new student in java programming, so I need your help I want to takes a function as its input a string of decimal integers, each character in the string can be thought of as a decimal digit. The digit should be converted to 3-bit binary string an packed into an int. I did the following code, but there is problem in converting 5 and 6 also I want the output like this 1234567 = 001 010 011 100 101 110 111 class Bin
{ public static void main(String []args) { String N=(args[0]); for(int i=0;i<N.length();i++) { String n=N.substring(i,i+1); int a=Integer.parseInt(n); int y=1,b; String z=""; for(a=a;a!=0; )
{ z=z+y; y=a&1; a=a>>1; }
b=Integer.parseInt(z); System.out.print(" "+b+" "); }
System.out.println(); } } Thanks, |
|
#2
|
|||
|
|||
|
I could not follow your code exactly, but this code quickly runs through the calculations needed until the number is complete
Code:
import java.io.*;
public class BinaryCalculator {
private static final int maxBytes = 3;
public static void main(String[] args) {
// we use a reader to read the inputs from the keyboard
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do {
try {
System.out.print("Type the number to parse: ");
// if the number cannot be parsed, an exception will be thrown and is catched further down
int number = Integer.parseInt(in.readLine());
int currentBit;
String result = "";
// this is where we calculate the number in the same manner as we would do by hand.
// since the maximum number of bytes are known, we can simply run through a for-loop,
// or we would have to make further calculations to figure out the size of the most-significant-bit
for (int i = maxBytes*8; i >= 0; i--) {
currentBit = 1 << i;
if (number >= currentBit) {
result += 1;
number -= currentBit;
}
else {
result += 0;
}
}
// and then printing the result to the screen
System.out.println(result);
}
// if we tried to parse a string that was not pure numbers, this will be thrown.
catch (NumberFormatException e) {
// the program exits
System.exit(0);
}
// if the reader threw an exception, something is wrong. alas, we print the stack-trace and exit
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
while (true);
}
}
__________________
Benjamin Horsleben horsleben.com/benjamin Don't blame malice for what stupidity can explain |
|
#3
|
|||
|
|||
|
for each character that you parse into your variable 'a' do the following (pseudocode):
Code:
for (x=0;x<3;++x) {
if ((a & 0x40)!=0)
print '1'
a<<=1
else
print '0'
}
print a space
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > please, Help me to convert String to Binary |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|