简体   繁体   中英

parseUnsignedInt - what's wrong with this method?

my mind going to blow up... What's going on with java?

I see that not only I have misunderstanding so maybe someone will tell me where is the logic of this implementation.

So we have this code

    String s = Integer.toBinaryString(-5);
    System.out.println(s);
    int i = Integer.parseInt(s, 2);
    System.out.println(i);

And of course we will get exception, because parseInt trying to parse 11111111111111111111111111111011 to 4 294 967 291 and of course this is out of range. BUT, why parseUnsignedInt parse 11111111111111111111111111111011 to -5 ??? Where is the logic? This is Unsigned! First of all I'm expecting that this method will return me unsigned Int ( I know that java doesn't have it ), but ok, let's try to imagine that parseUnsignedInt it's not about return value, it's about parameters, but again! If this is unsigned so 11111111111111111111111111111011 should be positive value, not -5 . Please tell me, what's the point? Because for me it looks like Sun\\Oracle is trolling developers.

PS I just tried to repeat this experiment in C#

        string s = Convert.ToString(-5, 2);
        Console.WriteLine(s);
        int i = Convert.ToInt32(s,2);
        Console.WriteLine(i);

and no problem. i = -5! As I expected. And also Convert.ToUInt32(s,2) will return me 4 294 967 291

UPDATE: Guys, maybe you don't understand me. I'm not looking for solution. I just confused that java core method contains "unsigned" word but has nothing to do with it. When you use parseUnsignedInt you expect that method will return you unsigned number. but -5 != unsigned number.

Integer.toBinaryString converts to two's complement format. use Integer.toString( -5, 2) if you want got get the binary digits. but it will be a leaded by '-' not '1'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM