I have binary String To Integer method implemented in my code. Problem is that I'm getting wrong last two digits of method output results, e.g.:
SHOULD BE RESULT : 11111111100001001000101110000100
RESULT : 11111111100001001000101110000011
There is always problem with last two digits of result.
Any help would be greatly appreciated.
code:
public static int binaryStringToInteger (String binaryString){
char[] digits = binaryString.toCharArray();
int binaryInteger = 0;
int count = 0;
for(int i=digits.length-1;i>=0;i--)
{
if(digits[i]=='1')
{
binaryInteger +=(int)Math.pow(2, count);
}
count++;
}
return binaryInteger;
}
There is nothing wrong with your code except int type can only hold so much. Int holds 4 bytes that is 8bitsx4 = 32 bits with the first one reserved for sign, negative if 1 and positive if 0. Try using long int which holds 64 bits:
public static long binaryStringToInteger (String binaryString){
char[] digits = binaryString.toCharArray();
long binaryInteger = 0;
int count = 0;
for(int i=digits.length-1;i>=0;i--)
{
if(digits[i]=='1')
{
binaryInteger +=(long)Math.pow(2, count);
}
count++;
}
return binaryInteger;
}
Also check this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments