Im looking for some help on this binary translator problem. The question goes: In this exercise, you’ll write a binary to text translator!
As we’ve seen, every character can be represented by a string of 8 bits, or a byte. For example, the binary string 010000012 has the decimal value of 6510, which maps to the character ‘A’.
So far I have this but the output is: H
CÞ*
NÒ)MØ
Here is my code:
public class Scratchpad extends ConsoleProgram
{
public void run()
{
System.out.println(binaryToText("0100100001001001"));
System.out.println(binaryToText("010000110110111101100100011001010100100001010011"));
System.out.println(binaryToText("010011100110100101100011011001010010000001001010011011110110001000100001"));
}
public String binaryToText(String binary)
{
String s2 = "";
char nextChar;
for(int i = 0; i <= binary.length()-8; i += 9) //this is a little tricky. we want [0, 7], [9, 16], etc (increment index by 9 if bytes are space-delimited)
{
nextChar = (char)Integer.parseInt(binary.substring(i, i+8), 2);
s2 += nextChar;
}
return s2;
}
public int binaryToDecimal(String binaryString)
{
int decimal = 0;
int base = 2;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1')
decimal += Math.pow(base,i);
}
return decimal;
}
}
Here is the solution:
For each string of bits, perform the following:
Create an array of 256 chars, the value of each element is the ASCII value of the index. For example, the value of element 65 is the character 'A'. This is the translationTable referenced below.
If the length of the string of bits is divisible by 8, continue.
If the string of bits contains only digits 0 and 1, continue.
Split the string of bits into smaller strings, each of which is exactly 8 digits in length.
For each 8-bit string, convert from binary to decimal.
Using the translationTable, convert from decimal to the desired ASCII character.
Accumulate the individual characters into a string (perhaps using a StringBuilder).
public class Scratchpad extends ConsoleProgram
{
public String binaryToText(String binary)
{
String s2 = "";
char nextChar;
for(int i = 0; i <= binary.length()-8; i += 8)
{
nextChar = (char)Integer.parseInt(binary.substring(i, i+8), 2);
s2 += nextChar;
}
return s2;
public int binaryToDecimal(String binaryString)
{
int numPlaces = binaryString.length();
int currentExponent = numPlaces - 1;
int decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++)
{
int placeValue = (int) Math.pow(2, currentExponent);
char currentDigit = binaryString.charAt(i);
int digitValue = Character.getNumericValue(currentDigit);
System.out.print(digitValue + " * (" + placeValue + ")");
if(i != binaryString.length() - 1)
{
System.out.print(" + ");
}
decimalValue += digitValue * placeValue;
currentExponent--;
}
System.out.println(" = " + decimalValue);
return decimalValue;
}
}
Related
Is there a known Java String with hashCode exactly equal to Integer.MIN_VALUE ? It would be helpful for writing a test for a hash table to help avoid a common mistake of running Math.Abs on the hashcode before performing the remainder operation.
Ideally the string would include only ASCII characters, but I'm not sure if it woul dbe feasible.
Based on the formula for hash code (from StringLatin1):
public static int hashCode(byte[] value) {
int h = 0;
for (byte v : value) {
h = 31 * h + (v & 0xff);
}
return h;
}
it depends linearly on the characters, the longer the string and greater the characters, the greater the hash code will be, until it overflows. Also note that the first characters have a greater impact on the resulting hash code (more often multiplied by 31).
The basic idea of the two first algorithm is to increment the characters until the hash code turns negative, starting with the left-most character since it has a greater weight. The searched string must have the character previous to the one that caused it to overflow on each position but the last one.
The code starts testing the strings "A", "AA", "AAA", ... until one starts returning a negative value - the previous string is used as starting value.
Now it starts incrementing the first character up to Z or until a string with a negative hash is found. The same is done for every next character.
Since the hash code of such strings was not yet reaching Integer.MIN_VALUE, an additional pass is done, to also test lowercase characters. This should have been integrated in the previous loop...
Now the last character is adjusted to exactly get to Integer.MIN_VALUE - simple since the last character is just added, without multiplication to calculate the hash code.
Here the code:
var string = "A";
while ((string+"A").hashCode() > 0) {
string += "A";
}
var array = string.toCharArray();
var i = 0;
while (i < array.length) {
array[i] += 1;
if (array[i] > 'z' || new String(array).hashCode() < 0) {
array[i] -= 1;
i += 1;
continue;
}
}
i = 1;
while (i < array.length) {
if (array[i] == 'Z') {
array[i] = 'a';
}else {
array[i] += 1;
}
if (array[i] > 'Z' || new String(array).hashCode() < 0) {
if (array[i] == 'a')
array[i] = 'Z';
else
array[i] -= 1;
i += 1;
continue;
}
}
int hash = new String(array).hashCode();
if (hash > 0) {
array[array.length-1] += Integer.MAX_VALUE - hash + 1;
}
System.out.printf("%s = %d%n", new String(array), new String(array).hashCode());
This results in:
HZcxf_ = -2147483648
Merging the two incrementing loops of previous code, we have:
var string = "A";
while ((string+"A").hashCode() > 0) {
string += "A";
}
var array = string.toCharArray();
var i = 0;
while (i < array.length) {
var prev = array[i];
if (prev == 'Z') {
array[i] = 'a';
} else {
array[i] += 1;
}
if (array[i] > 'z' || new String(array).hashCode() < 0) {
array[i] = prev;
i += 1;
continue;
}
}
int hash = new String(array).hashCode();
if (hash > 0) {
array[array.length-1] += Integer.MAX_VALUE - hash + 1;
}
System.out.printf("%s = %d%n", new String(array), new String(array).hashCode());
Resulting in (slightly different than previous):
HZdZG_ = -2147483648
Another method would be more strongly based on the hash calculation, basically undoing it.
Since I did not want to work with negative number, it starts with Integer.MAX_VALUE, which is one less than Integer.MIN_VALUE (considering over/underflow).
First it finds out how often it must be divided by 31 until the result is less than 128 (ASCII), kind of determining the string length.
Next it loops and finds out each character with some special handling to avoid characters less than ' '.
At the end, the last character is incremented by one to move the hash code from MAX_VALUE to MIN_VALUE by overflowing.
var string = "";
var remain = Integer.MAX_VALUE;
var i = 0;
var multiplier = 1;
while (remain > 127) {
remain /= 31;
multiplier *= 31;
i += 1;
}
remain = Integer.MAX_VALUE;
while (i >= 0) {
var ch = (char)(remain / multiplier);
remain -= ch * multiplier;
multiplier /= 31;
if (i > 0) {
// correct if next ch will be less than ' '
var correct = (' ' - (remain / multiplier) + 30) / 31; // old fashion rounding
if (correct > 0) {
ch -= correct;
remain += correct * 31 * multiplier;
}
} else {
ch += 1;
}
string += ch;
i -= 1;
}
System.out.printf("%s = %d%n", string, string.hashCode());
And its results:
I='<*! = -2147483648
Note: the last code will definitively fail if the hash code algorithm of String is changed! The previous two may fail, depending on how the hash calculation is changed.
String#hashCode() is defined as:
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
Now you just need to solve for -2147483648 (perhaps with the restriction of only printable ASCII chars: 32–127) :)
Or you brute-force (this will take a while):
public class HashFinder {
private static final int SIZE = 7;
private static long hashesCalculated = 0L;
public static void main(String[] args) {
hashesCalculated = 0L;
final long start = System.nanoTime();
findHash(SIZE);
final long duration = System.nanoTime() - start;
System.err.println("Checked strings of size " + SIZE);
System.err.println(hashesCalculated + " hashes in " + TimeUnit.NANOSECONDS.toSeconds(duration) + "s");
}
public static void findHash(final int size) {
findHash("", size);
}
public static void findHash(final String prefix, final int size) {
if (size <= 0) {
return;
}
final StringBuilder sb = new StringBuilder(prefix).append(' ');
for (char c = ' '; c < '~'; ++c) {
sb.setCharAt(prefix.length(), c);
final String s = sb.toString();
++hashesCalculated;
if (s.hashCode() == Integer.MIN_VALUE) {
System.out.printf("Found string with min hashCode! '%s'%n", s);
}
findHash(s, size - 1);
}
}
}
But allocating all those strings and string builders is expensive. Brute-forcing becomes feasible when we calculate the hash code manually from a char array:
public class HashFinderBytes {
public static void main(String[] args) {
final char start = ' ', end = '~';
for (int size = 1; size <= 9; size++) {
char[] chars = new char[size];
Arrays.fill(chars, start);
final long startNano = System.nanoTime();
final long combinations = BigInteger.valueOf(end - start).pow(size).longValue();
System.err.println("Checking " + combinations + " strings of size " + size);
for (long i = 0; i < combinations; ++i) {
if (hashCode(chars) == Integer.MIN_VALUE) {
System.out.printf("Found string with min hashCode! \"%s\"%n", new String(chars));
System.out.println("Sanity check: " + (new String(chars).hashCode() == Integer.MIN_VALUE));
}
for (int j = 0; j < chars.length; ++j) {
++chars[j];
if (chars[j] <= end) {
break;
}
chars[j] = (byte) start;
}
}
final long duration = System.nanoTime() - startNano;
final long millis = TimeUnit.NANOSECONDS.toMillis(duration);
System.err.println("in " + millis + "ms (" + (combinations / millis) + " ops/ms)");
}
}
public static int hashCode(char[] value) {
int h = 0;
for (char v : value) {
h = 31 * h + (v & 0xff);
}
return h;
}
}
In fact, there are lots of strings with a hash code identical to Integer.MIN_VALUE.
Length 6:
I='<*!
H\'<*!
G{'<*!
I<F<*!
H[F<*!
GzF<*!
I;e<*!
HZe<*!
Gye<*!
I=&[*!
H\&[*!
G{&[*!
I<E[*!
H[E[*!
GzE[*!
I;d[*!
HZd[*!
Gyd[*!
I=%z*!
H\%z*!
G{%z*!
I<Dz*!
H[Dz*!
GzDz*!
I;cz*!
HZcz*!
Gycz*!
I=';I!
H\';I!
G{';I!
I<F;I!
H[F;I!
GzF;I!
I;e;I!
HZe;I!
Gye;I!
I=&ZI!
H\&ZI!
G{&ZI!
I<EZI!
H[EZI!
GzEZI!
I;dZI!
HZdZI!
GydZI!
I=%yI!
H\%yI!
G{%yI!
I<DyI!
H[DyI!
GzDyI!
I;cyI!
HZcyI!
GycyI!
I=':h!
H\':h!
G{':h!
I<F:h!
H[F:h!
GzF:h!
I;e:h!
HZe:h!
Gye:h!
I=&Yh!
H\&Yh!
G{&Yh!
I<EYh!
H[EYh!
GzEYh!
I;dYh!
HZdYh!
GydYh!
I=%xh!
H\%xh!
G{%xh!
I<Dxh!
H[Dxh!
GzDxh!
I;cxh!
HZcxh!
Gycxh!
Length 7 (all of the strings below end with a space character); not all shown:
p4*|{e
oS*|{e
nr*|{e
p3I|{e
oRI|{e
nqI|{e
p2h|{e
oQh|{e
nph|{e
I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == sum;
}
The program is simple in concept: I simply need to print a space between every 8 numbers, and there needs to be a space in front of the first digit. It should look something like this: 65536(10) = 1 00000000 00000000. However, I am not sure how to write this code. I tried using the split method, but it didn't work, and now I'm trying this:
String binaryStr = "";
int saveInt, intValue, quotient, remainder;
int cnt = 0;
System.out.println ("\n(7) Converting an unsigned Integer to binary.");
System.out.print ("Enter an integer value: ");
intValue = kb.nextInt();
if (intValue >= 0)
{
saveInt = intValue;
while (intValue > 0)
{
remainder = intValue % 2;
intValue = intValue / 2;
binaryStr = (char)(remainder+48) + binaryStr;
for (cnt = binaryStr.length(); cnt < 9; ++cnt) //I tried this to split btwn every 8 spaces.
//Not sure how to space after first digit.
System.out.print(" ");
}
System.out.printf ("After Conversion: %d(10) = %s(2).\n", saveInt, binaryStr);
}
I appreciate any help. Thanks!
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
System.out.println("(7) Converting an unsigned Integer to binary.");
System.out.print("Enter an integer value: ");
int num = scan.nextInt();
String binaryStr = convertToBinary(num);
System.out.printf("After Conversion: %d(10) = %s(2).\n", num, binaryStr);
}
public static String convertToBinary(int num) {
String str = Integer.toBinaryString(num);
StringBuilder buf = new StringBuilder(str.length() + 5);
for (int i = str.length() - 1, j = 0; i >= 0; i--, j++) {
if (j > 0 && j % 8 == 0)
buf.append(' ');
buf.append(str.charAt(i));
}
return buf.reverse().toString();
}
Output:
(7) Converting an unsigned Integer to binary.
Enter an integer value: 65536
After Conversion: 65536(10) = 1 00000000 00000000(2).
I have converted some decimal numbers into the binary, octal and hexadecimal system. For that, I didn't have to use any collections and libraries. So now I need to change my implementation because I used String for storing the result, while I supposed to use a char array.
My current implementation:
public static String convertDecimal(int number, int base){
String result = "";
while (number > 0) {
if (base == 16) {
int hexalNumber = number % base;
char hexDigit = (hexalNumber <= 9 && hexalNumber > 0) ?
(char) (hexalNumber + '0') :
(char) (hexalNumber - 10 + 'A');
result = hexDigit + result;
number = number / base;
}
if (base == 8 || base == 2) {
int remainder = number % base;
result = remainder + result;
number = number / base;
}
}
return result;
}
How can I change my implementation in order to return char[] from the method? Should I completely change the logic of my conversion algorithm?
I would be grateful for any help.
String has a method for converting itself to a char[], just use it:
return result.toCharArray();
If they want an array of char, they probably won't like just a
return result.toCharArray();
As arrays are of fixed size, one could first count the digits:
public static char[] convertDecimal(int number, int base) {
if (number < 0) {
char[] positiveResult = convertDecimal(-number, base);
char[] negativeResult = ...
return negativeResult;
} else if (number == 0) {
return new char[] { '0' };
}
int digits = 0;
int n = number;
while (n != 0) {
++digits;
n /= base;
}
char[] result = new char[digits];
for (int i = 0; i < digits; ++i) {
... result[... i ...] = ...; ++i
}
return result;
}
I have tested this in your code:
convertDecimal(7856421, 16);
For this call and editing your code as following (I have not deleted any line, only added I have added the car[]):
public static String convertDecimal(int number, int base) {
char[] resultChar = new char[0];
String result = "";
while (number > 0) {
if (base == 16) {
int hexalNumber = number % base;
char hexDigit = (hexalNumber <= 9 && hexalNumber > 0) ? (char) (hexalNumber + '0')
: (char) (hexalNumber - 10 + 'A');
result = hexDigit + result;
int totalLength = resultChar.length + 1;
char[] aux = new char[totalLength];
int i = 0;
for (i = 0; i < resultChar.length; i++) {
aux[i] = resultChar[i];
}
aux[totalLength - 1] = hexDigit;
resultChar = aux;
number = number / base;
}
if (base == 8 || base == 2) {
int remainder = number % base;
result = remainder + result;
number = number / base;
}
}
return result;
}
Yo have in resultChar[] the result inverted (in this case you get 77E125 and the char[] has [5, 2, 1, E, 7, 7]). now you only need to return it inverted.
I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:
binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary 11 becomes integer 3 etc.
What's the best way to proceed? I've been exploring java.lang.number.* without finding a direct conversion method. Integer.parseInt(b) yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. toBinaryString does the conversion the wrong direction. I suspect I'll need to do a multistep conversion, but can't seem to find the right combination of methods or subclasses. I'm also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?
You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.
int foo = Integer.parseInt("1001", 2);
This might work:
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
int foo = Integer.parseInt("1001", 2);
works just fine if you are dealing with positive numbers but if you need to deal with signed numbers you may need to sign extend your string then convert to an Int
public class bit_fun {
public static void main(String[] args) {
int x= (int)Long.parseLong("FFFFFFFF", 16);
System.out.println("x =" +x);
System.out.println(signExtend("1"));
x= (int)Long.parseLong(signExtend("1"), 2);
System.out.println("x =" +x);
System.out.println(signExtend("0"));
x= (int)Long.parseLong(signExtend("0"), 2);
System.out.println("x =" +x);
System.out.println(signExtend("1000"));
x= (int)Long.parseLong(signExtend("1000"), 2);
System.out.println("x =" +x);
System.out.println(signExtend("01000"));
x= (int)Long.parseLong(signExtend("01000"), 2);
System.out.println("x =" +x);
}
private static String signExtend(String str){
//TODO add bounds checking
int n=32-str.length();
char[] sign_ext = new char[n];
Arrays.fill(sign_ext, str.charAt(0));
return new String(sign_ext)+str;
}
}
output:
x =-1
11111111111111111111111111111111
x =-1
00000000000000000000000000000000
x =0
11111111111111111111111111111000
x =-8
00000000000000000000000000001000
x =8
I hope that helps!
static int binaryToInt (String binary){
char []cA = binary.toCharArray();
int result = 0;
for (int i = cA.length-1;i>=0;i--){
//111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
// 0 1
if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
}
return result;
}
public Integer binaryToInteger(String binary){
char[] numbers = binary.toCharArray();
Integer result = 0;
int count = 0;
for(int i=numbers.length-1;i>=0;i--){
if(numbers[i]=='1')result+=(int)Math.pow(2, count);
count++;
}
return result;
}
I guess I'm even more bored! Modified Hassan's answer to function correctly.
For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.
System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));
Output : -9
Using bitshift is more elegant and faster than Math.pow. Simply bitshift the digits (0 or 1) into position with val <<= 1
// parse an unsigned binary string, valid up to 31 bits
static int binaryToBase10(String binaryString) {
int val = 0;
for (char c : binaryString.toCharArray()) {
val <<= 1;
val += c-'0';
}
return val;
}
Example use
int val = binaryToBase10("1011");
System.out.println(val);
prints 11
Fixed version of java's Integer.parseInt(text) to work with negative numbers:
public static int parseInt(String binary) {
if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);
int result = 0;
byte[] bytes = binary.getBytes();
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] == 49) {
result = result | (1 << (bytes.length - 1 - i));
}
}
return result;
}
I love loops! Yay!
String myString = "1001001"; //73
While loop with accumulator, left to right (l doesn't change):
int n = 0,
j = -1,
l = myString.length();
while (++j < l) n = (n << 1) + (myString.charAt(j) == '0' ? 0 : 1);
return n;
Right to left with 2 loop vars, inspired by Convert boolean to int in Java (absolutely horrible):
int n = 0,
j = myString.length,
i = 1;
while (j-- != 0) n -= (i = i << 1) * new Boolean(myString.charAt(j) == '0').compareTo(true);
return n >> 1;
A somewhat more reasonable implementation:
int n = 0,
j = myString.length(),
i = 1;
while (j-- != 0) n += (i = i << 1) * (myString.charAt(j) == '0' ? 0 : 1);
return n >> 1;
A readable version :p
int n = 0;
for (int j = 0; j < myString.length(); j++) {
n *= 2;
n += myString.charAt(j) == '0' ? 0 : 1;
}
return n;
Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.
public static String decimalToBinaryString(int value) {
String str = "";
while(value > 0) {
if(value % 2 == 1) {
str = "1"+str;
} else {
str = "0"+str;
}
value /= 2;
}
return str;
}
You can also use this method to convert the binary to decimal integer if you are given with string.(Java Language)
static int binaryTodecimal(String s){
int i= -1;
char[] str = s.toCharArray();
int dec_val= 0;
for (int j=str.length-1; j>=0 ;j-- ){
int k= Integer.valueOf(str[j]) - '0';
i = i+1;
dec_val += k*(Math.pow(2, i));
}
System.out.println(dec_val);
}
If you're worried about performance, Integer.parseInt() and Math.pow() are too expensive. You can use bit manipulation to do the same thing twice as fast (based on my experience):
final int num = 87;
String biStr = Integer.toBinaryString(num);
System.out.println(" Input Number: " + num + " toBinary "+ biStr);
int dec = binaryStringToDecimal(biStr);
System.out.println("Output Number: " + dec + " toBinary "+Integer.toBinaryString(dec));
Where
int binaryStringToDecimal(String biString){
int n = biString.length();
int decimal = 0;
for (int d = 0; d < n; d++){
// append a bit=0 (i.e. shift left)
decimal = decimal << 1;
// if biStr[d] is 1, flip last added bit=0 to 1
if (biString.charAt(d) == '1'){
decimal = decimal | 1; // e.g. dec = 110 | (00)1 = 111
}
}
return decimal;
}
Output:
Input Number: 87 toBinary 1010111
Output Number: 87 toBinary 1010111