David
David

Reputation: 13

Convert 32 bit binary number to decimal

someone who can help me I have the following drawback,   to enter a negative decimal binary in this case enter -20 (11000001101000000000000000000000) throws me the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11000001101000000000000000000000"

# Include  <stdio.h> 
# include  <stdlib.h>

public static void main(String[] args) {       
    int bits = Integer.parseInt("1000001101000000000000… 2);        
    float f1 = Float.intBitsToFloat(bits);
    int Sign = ((bits >> 31) == 0) ? 1 : -1;
    int Exponent = ((bits >> 23) & 0xff);
    int Mantissa = (Exponent== 0)
    ? (bits & 0x7fffff) << 1
    : (bits & 0x7fffff) | 0x800000;
    System.out.println("Sign: " + Sign + " Exponent: " + Exponent + "Mantissa:" + Mantissa);
    System.out.println(f1);
}

Upvotes: 0

Views: 4221

Answers (1)

Pshemo
Pshemo

Reputation: 124215

From Integer.#parseInt(java.lang.String, int):

...The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value)...

Unfortunately you want to parse negative value. You could try using Long.parseLong instead and cast returned long to int

int bits = (int) Long.parseLong("11000001101000000000000000000000", 2);

This way you will get your int that has same byte representation

System.out.println(">"+Integer.toBinaryString(bits));

output:

>11000001101000000000000000000000

Upvotes: 1

Related Questions