简体   繁体   English

parseUnsignedInt - 这个方法有什么问题?

[英]parseUnsignedInt - what's wrong with this method?

my mind going to blow up... What's going on with java?我的脑子要炸了……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.当然我们会得到异常,因为 parseInt 试图解析 11111111111111111111111111111011 到 4 294 967 291,当然这超出了范围。 BUT, why parseUnsignedInt parse 11111111111111111111111111111011 to -5 ???但是,为什么parseUnsignedInt解析 11111111111111111111111111111011 到 -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!首先,我期待这个方法会返回给我 unsigned Int (我知道 java 没有它),但是好吧,让我们试着想象parseUnsignedInt它不是关于返回值,而是关于参数,但又一次! If this is unsigned so 11111111111111111111111111111011 should be positive value, not -5 .如果这是无符号的,那么 11111111111111111111111111111011 应该是正值,而不是-5 Please tell me, what's the point?请告诉我,有什么意义? Because for me it looks like Sun\\Oracle is trolling developers.因为对我来说,Sun\\Oracle 似乎在控制开发人员。

PS I just tried to repeat this experiment in C# PS 我只是尝试在 C# 中重复这个实验

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

and no problem.没有问题。 i = -5!我 = -5! As I expected.正如我所料。 And also Convert.ToUInt32(s,2) will return me 4 294 967 291而且 Convert.ToUInt32(s,2) 将返回我 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.我只是混淆了 java 核心方法包含“无符号”词但与它无关。 When you use parseUnsignedInt you expect that method will return you unsigned number.当您使用parseUnsignedInt 时,您希望该方法将返回无符号数。 but -5 != unsigned number.但是 -5 != 无符号数。

Integer.toBinaryString converts to two's complement format. Integer.toBinaryString 转换为二进制补码格式。 use Integer.toString( -5, 2) if you want got get the binary digits.如果你想得到二进制数字,请使用 Integer.toString( -5, 2) 。 but it will be a leaded by '-' not '1'.但它将以“-”而不是“1”开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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