Convert from decimal to binary, octal, hexadecimal with char array - java

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.

Related

How to convert from base 10 to base x in java?

What i've done so far:
public static String convert(int base, int target , String number) {
ArrayList<Integer> numbers= new ArrayList<Integer>();
for(int i=0;i<number.length();i++) {
char check=number.charAt(i);
if(check>='A') {
numbers.add(Character.getNumericValue(check-'A'+1));
}
else {
numbers.add(Character.getNumericValue(check));
}
}
int answer_10 = 0;
for(int i=0;i<number.length();i++) {
answer_10 += Math.pow(numbers.get(number.length()-i-1), base);
}
String answer_target ="";
while(answer_10>0) { // I need help on this part
for(int i=0;i>0;i++) {
if(9*Math.pow(target, i)-answer_10<0) {
i++;
}
else {
for(int j=9;j<=0;j--) {
if(j*Math.pow(target, i)-answer_10<0) {
j-=1;
if(j<=10) {
answer_target += j*Math.pow(target, i);
}
else {
answer_target += j-'A'+1 ;
}
answer_10 -= j*Math.pow(target, i);
break;
}
}
}
}
}
return answer_target;
}
I need help on the part that converts the number from base 10 to base x as a string.
The question limits 2<=x<=20.
I couldn't use the built-in converting function by java, as the question asked not to.
Math.pow isn't a good choice for this problem. It is better to use simple multiply /divide cycle.
public static String convert(int base, int target, String number) {
if (base < 2 || base > 20)
throw new IllegalArgumentException("Invalid base "+base);
if (target < 2 || target > 20)
throw new IllegalArgumentException("Invalid base "+target);
int numberStrLen = number.length();
int numberValue = 0;
for (int i = 0; i < numberStrLen; i++) {
char ch = Character.toLowerCase(number.charAt(i));
int digit;
if (ch >= '0' && ch <= '9')
digit = ch - '0';
else if (ch >= 'a')
digit = ch - 'a' + 10;
else
throw new IllegalArgumentException("Invalid character "+ch+" for base "+base);
if (digit >= base)
throw new IllegalArgumentException("Invalid character "+ch+" for base "+base);
numberValue = numberValue * base + digit; // <= multiply cycle
}
if (numberValue < 0)
throw new IllegalArgumentException("Signed value: "+numberValue+" for "+number);
StringBuilder sb = new StringBuilder();
while (numberValue != 0) {
int digit = numberValue % target;
numberValue = numberValue / target; // <= divide cycle
char ch;
if (digit < 10)
ch = (char)(digit + '0');
else
ch = (char)(digit - 10 + 'a');
sb.insert(0, ch);
}
if (sb.length() == 0)
return "0";
else
return sb.toString();
}
And don't forget about int overflow (wraparound ). Maybe use long or even BigInteger?

What is causing StackoverFlowError in my code?

I need to write two recusion methods. One of them checks candidate values which need to be enumerated from its most-significant to least-significant digits. For example if numbers are in three-digits it need to be 124 126 128 134 136 138 146 148 156 and so on up to 999 (also even).
I wrote two of them there is no problem in one, two and three digits however, after four digits something cause java.lang.StackOverflowError
How can I solve this problem ?
public boolean checkRec(int num)
{
String numLong = String.valueOf(num);
if((Integer.valueOf(numLong.substring(numLong.length()-1)) % 2) != 0)
return false;
if(numLong.length() == 1)
return true;
else
{
if(Integer.valueOf(numLong.substring(0,1)) >= Integer.valueOf(numLong.substring(1,2)))
{
// System.out.println("asd");
return false;
}
numLong = numLong.substring(1);
num = Integer.valueOf(numLong);
return checkRec(num);
}
}
public String orderAndPrint(int num, int decimal)
{
if(num >= Math.pow(10, decimal+1))
return "End";
else
{
if(checkRec(num))
{
return "" + num + " " + orderAndPrint((num + 2), decimal);
}
return orderAndPrint((num + 2), decimal);
}
You do like recursions :-). How about this function pair:
public boolean check(int num)
{
// This is actually unnecessary as check is called only for even numbers
if ((num % 2) != 0)
return false;
int prev_digit = 10;
while (num > 0) {
int last_digit = num % 10;
if (last_digit >= prev_digit)
return false;
prev_digit = last_digit;
num = num / 10;
}
return true;
}
public String orderAndPrint(int decimal)
{
String outstr = ""
int last_num = Math.pow(10, decimal);
int num = 2;
for ( ; num < last_num; num += 2) {
if (check(num))
outstr = outstr + num + " ";
}
return outstr + "End";
}
But, this piece of code just replicates what you have done more efficiently, without recursion.
However, you can code to just generate the appropriate numbers, and there you actually need recursion. Note that the largest possible such number is 12345678, so the max number of digits is 8 and all such numbers fit into an int. Also, none of the digits will be greater than 8, and only the last may be 8.
public String addnumbers (int n, int digitsleft, String outstr)
{
int d;
int last_digit = n % 10;
if (digitsleft == 1) {
d = (last_digit+1) % 2 == 0 ? last_digit+1 : last_digit+2;
for ( ; d <= 8; d += 2) {
outstr = outstr + (10*n+d) + " ";
}
}
else {
for (d=last_digit+1; d < 8; ++d) {
outstr = addnumbers(10*n+d, digitsleft-1, outstr);
}
}
return outstr;
}
public String orderAndPrint(int decimal)
{
// Assume decimal is at least 1
String outstr = "2 4 6 8 "
int d;
decimal = Math.min(8, decimal);
for (d = 1; d < 8; ++d) {
outstr = addnumbers(d, decimal-1, outstr);
}
return outstr + "End";
}
Note that this could be further sped up by using a better upper bound on d in the loops. For example, if after the current one there are still 2 more digits, then d can't be larger than 6. But that would have just obfuscated the code.

How to get 2's complement of a binary number in Java programmatically

How to calculate the 2's Complement of a Hex number in Android/Java.
For Example :
String x = 10011010;
1's complement of x = 01100101;
2's complement is 01100110;
How I can pro-grammatically achieve in Java?
I had tried the following code to convert the binary to its 1's compliment:
public String complementFunction(String bin) {
String ones = "";
for (int i = 0; i < bin.length(); i++) {
ones += flip(bin.charAt(i));
}
return ones;
}
// Returns '0' for '1' and '1' for '0'
public char flip(char c) {
return (c == '0') ? '1' : '0';
}
But I'm not able to get its two's complement.
Thanks for your help everyone.
I got the solution and it is as follows :
public String twosCompliment(String bin) {
String twos = "", ones = "";
for (int i = 0; i < bin.length(); i++) {
ones += flip(bin.charAt(i));
}
int number0 = Integer.parseInt(ones, 2);
StringBuilder builder = new StringBuilder(ones);
boolean b = false;
for (int i = ones.length() - 1; i > 0; i--) {
if (ones.charAt(i) == '1') {
builder.setCharAt(i, '0');
} else {
builder.setCharAt(i, '1');
b = true;
break;
}
}
if (!b)
builder.append("1", 0, 7);
twos = builder.toString();
return twos;
}
// Returns '0' for '1' and '1' for '0'
public char flip(char c) {
return (c == '0') ? '1' : '0';
}
Thanks to all for helping.
This wikipedia section explains an easy way to get the 2's complement: Get the 1's complement, then add 1 (in binary logic). So you can use the complementFunction you already have, then go through the String backwards. If you find a 1, flip it and continue. If you find a 0, flip it and stop.
String twos = "";
for (int i = bin.length() - 1; i >= 0; i--) {
if (bin.charAt(i) == '1') {
twos = "0" + twos;
} else {
twos = bin.substring(0, i) + "1" + two;
break;
}
twos = flip(bin.charAt(i));
}
return twos;
#BackSlash's comment above is intriguing. This answer is the full program written based on this idea:
import java.time.temporal.ValueRange;
import java.util.Scanner;
//This program generates convert decimal to binary
public class ConvertDecimalToBinary {
public static int getNumberOfBytes(int n) {
int bytes = 0;
ValueRange byteRange = ValueRange.of(Byte.MIN_VALUE, Byte.MAX_VALUE);
ValueRange shortRange = ValueRange.of(Short.MIN_VALUE, Short.MAX_VALUE);
ValueRange intRange = ValueRange.of(Integer.MIN_VALUE, Integer.MAX_VALUE);
if (byteRange.isValidValue(n)) {
bytes = 1;
} else if (shortRange.isValidValue(n)) {
bytes = 2;
} else if (intRange.isValidValue(n)) {
bytes = 4;
}
return bytes;
}
//Convert a positive decimal number to binary
public static String convertPositiveNumberToBinary(int n, int bytes,boolean reverse) {
int bits = 8 * bytes;
StringBuilder sb = new StringBuilder(bits); //in-bits
if (n == 0) {
sb.append("0");
} else {
while (n > 0) {
sb.append(n % 2);
n >>= 1; //aka n/2
}
}
if (sb.length() < bits) {
for (int i = sb.length(); i < bits; i++) {
sb.append("0");
}
}
if (reverse) {
return sb.toString();
} else {
return sb.reverse().toString();
}
}
//Convert negative decimal number to binary
public static String convertNegativeNumberToBinary(int n, int bytes) {
int m = -n; //conver to positve
String binary = convertPositiveNumberToBinary(m,bytes,true);
int len = binary.length();
StringBuilder sb = new StringBuilder(len); //in-bits
boolean foundFirstOne = false;
for(int i=0; i < len;i++) {
if(foundFirstOne) {
if(binary.charAt(i) == '1') {
sb.append('0');
}
else {
sb.append('1');
}
}
else {
if(binary.charAt(i) == '1') {
foundFirstOne = true;
}
sb.append(binary.charAt(i));
}
}
return sb.reverse().toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt()) {
int n = scanner.nextInt();
int bytes = getNumberOfBytes(n);
String binary;
if(n >= 0) {
binary = convertPositiveNumberToBinary(n,bytes,false);
}
else {
binary = convertNegativeNumberToBinary(n,bytes);
}
System.out.println(String.format("Binary representation of {%s} is {%s}",n,binary));
}
scanner.close();
}
}

Converting binary string to a hexadecimal string JAVA

I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:
//the variable name of the binary string is: "binary"
int digitNumber = 1;
int sum = 0;
int test = binary.length()%4;
if(test!=0) {
binary = padLeft(binary, test);
}
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
public static String padLeft(String s, int n) {
return String.format("%0$"+n+"s", s);
}//i added this for padding
the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:
http://www.wikihow.com/Convert-Binary-to-Hexadecimal
PS: I need to implement it(not using any built-in function)
If you don't have to implement that conversion yourself, you can use existing code :
int decimal = Integer.parseInt(binaryStr,2);
String hexStr = Integer.toString(decimal,16);
If you must implement it yourself, there are several problems in your code :
The loop should iterate from 0 to binary.length()-1 (assuming the first character of the String represents the most significant bit).
You implicitly assume that your binary String has 4*x charcters for some integer x. If that's not true, your algorithm breaks. You should left pad your String with zeroes to get a String of such length.
sum must be reset to 0 after each hex digit you output.
System.out.print(digitNumber); - here you should print sum, not digitNumber.
Here's how the mostly fixed code looks :
int digitNumber = 1;
int sum = 0;
String binary = "011110101010";
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
Output :
7AA
This will work only if the number of binary digits is divisable by 4, so you must add left 0 padding as a preliminray step.
Use this for any binary string length:
String hexString = new BigInteger(binaryString, 2).toString(16);
You can try something like this.
private void bitsToHexConversion(String bitStream){
int byteLength = 4;
int bitStartPos = 0, bitPos = 0;
String hexString = "";
int sum = 0;
// pad '0' to make input bit stream multiple of 4
if(bitStream.length()%4 !=0){
int tempCnt = 0;
int tempBit = bitStream.length() % 4;
while(tempCnt < (byteLength - tempBit)){
bitStream = "0" + bitStream;
tempCnt++;
}
}
// Group 4 bits, and find Hex equivalent
while(bitStartPos < bitStream.length()){
while(bitPos < byteLength){
sum = (int) (sum + Integer.parseInt("" + bitStream.charAt(bitStream.length()- bitStartPos -1)) * Math.pow(2, bitPos)) ;
bitPos++;
bitStartPos++;
}
if(sum < 10)
hexString = Integer.toString(sum) + hexString;
else
hexString = (char) (sum + 55) + hexString;
bitPos = 0;
sum = 0;
}
System.out.println("Hex String > "+ hexString);
}
Hope this helps :D
import java.util.*;
public class BinaryToHexadecimal
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the binary number");
double s=sc.nextDouble();
int c=0;
long s1=0;
String z="";
while(s>0)
{
s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
s=(long)s/10;
c++;
}
while(s1>0)
{
long j=s1%16;
if(j==10)
{
z="A"+z;
}
else if(j==11)
{
z="B"+z;
}
else if(j==12)
{
z="C"+z;
}
else if(j==13)
{
z="D"+z;
}
else if(j==14)
{
z="E"+z;
}
else if(j==15)
{
z="F"+z;
}
else
{
z=j+z;
}
s1=s1/16;
}
System.out.println("The respective Hexadecimal number is : "+z);
}
}
By given binary number 01011011, we will convert it at first to decimal number, each number will be Math.pow() by decrementd length:
01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (1 × 2(4)) + (1 × 2(3)) + (0 × 2(2)) + (1 × 2(1)) + (1 × 2(0))
= (0 × 128) + (1 × 64) + (0 × 32) + (1 × 16) + (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)
= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1
= 91 (decimal form of binary number)
Now after get decimal number we have to convert it to hexa-decimal-number.
So, 91 is greater than 16. So, we have to divide by 16.
After dividing by 16, quotient is 5 and remainder is 11.
Remainder is less than 16.
Hexadecimal number of remainder is B.
Quotient is 5 and hexadecimal number of remainder is B.
That is, 91 = 16 × 5 +11 = B
5 = 16 × 0 + 5 = 5
=5B
Implementation:
String hexValue = binaryToHex(binaryValue);
//Display result
System.out.println(hexValue);
private static String binaryToHex(String binary) {
int decimalValue = 0;
int length = binary.length() - 1;
for (int i = 0; i < binary.length(); i++) {
decimalValue += Integer.parseInt(binary.charAt(i) + "") * Math.pow(2, length);
length--;
}
return decimalToHex(decimalValue);
}
private static String decimalToHex(int decimal){
String hex = "";
while (decimal != 0){
int hexValue = decimal % 16;
hex = toHexChar(hexValue) + hex;
decimal = decimal / 16;
}
return hex;
}
private static char toHexChar(int hexValue) {
if (hexValue <= 9 && hexValue >= 0)
return (char)(hexValue + '0');
else
return (char)(hexValue - 10 + 'A');
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stringprocessing;
/**
*
* #author Zayeed Chowdhury
*/
public class StringProcessing {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int index = 0;
String bin = "0000000101100101011011100110011100000001000000000000000010101010010101100110010101100011011010010110110101100001001000000100111001100101011101000111011101101111011100100110101101110011001000000100100001000001010100110010000001001001010100110101001101010101010001010100010000100000010000010010000001010010010001010101000101010101010010010101001001000101010001000010000001010111010001010100010101001011010011000101100100100000010101000100010101010011010101000010000001000110010011110101001000100000010101000100100001000101001000000100011001001111010011000100110001001111010101110100100101001110010001110010000001000011010011110101010101001110010101000100100101000101010100110010111101000001010100100100010101000001010100110011101000100000010100000110100101101110011000010110110000101100001000000100000101011010001110110010000001000001010101000010000000000001111000000011000100110010001110100011000100110011001000000101000001001101001000000100111101001110";
String[] hexString = new String[bin.length() / 4];
for (int i = 0; i < bin.length() / 4; i++) {
hexString[i] = "";
for (int j = index; j < index + 4; j++) {
hexString[i] += bin.charAt(j);
}
index += 4;
}
for (int i = 0; i < bin.length() / 4; i++) {
System.out.print(hexString[i] + " ");
}
System.out.println("\n" + bin.length());
String[] result = binaryToHex(hexString);
for (int i = 0; i < result.length; i++) {
System.out.print("" + result[i].toUpperCase());
}
System.out.println("");
}
public static String[] binaryToHex(String[] bin) {
String[] result = new String[bin.length];
for (int i = 0; i < bin.length; i++) {
result[i] = Integer.toHexString(Integer.parseInt(bin[i], 2));
}
//return Integer.toHexString(Integer.parseInt(bin[0], 2));
return result;
}
}
private final String[] hexValues = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
public void binaryToHexadecimal(String binary){
String hexadecimal;
binary = leftPad(binary);
System.out.println(convertBinaryToHexadecimal(binary));
}
public String convertBinaryToHexadecimal(String binary){
String hexadecimal = "";
int sum = 0;
int exp = 0;
for (int i=0; i<binary.length(); i++){
exp = 3 - i%4;
if((i%4)==3){
sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
hexadecimal = hexadecimal + hexValues[sum];
sum = 0;
}
else
{
sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
}
}
return hexadecimal;
}
public String leftPad(String binary){
int paddingCount = 0;
if ((binary.length()%4)>0)
paddingCount = 4-binary.length()%4;
while(paddingCount>0) {
binary = "0" + binary;
paddingCount--;
}
return binary;
}

How to convert a Binary String to a base 10 integer in Java

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

Categories