Wrapper 的 parseXXX() 用于有符号二进制误解 [英] Wrapper's parseXXX() for signed binary misunderstanding

查看:22
本文介绍了Wrapper 的 parseXXX() 用于有符号二进制误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们以Byte.parseByte()为例,作为包装器的parseXXX()之一.

Let's take Byte.parseByte() as an example as one of the wrappers' parseXXX().

来自 parseByte(String s, int radix) 的 JavaDoc:

将字符串参数解析为指定的基数中的有符号字节第二个参数.

Parses the string argument as a signed byte in the radix specified by the second argument.

但如果 radix = 2 就不太正确了.换句话说,-127 的二进制字面量是 10000000:

But that's not quite true if radix = 2. In other words, the binary literal of -127 is 10000000:

byte b = (byte) 0b10000000;

所以以下应该是正确的:

So the following should be true:

byte b = Byte.parseByte("10000000", 2);

但不幸的是,它抛出了NumberFormatException,而我必须这样做:

but unfortunately, it throws NumberFormatException, and instead I have to do it as follows:

byte b = Byte.parseByte("-111111", 2);

where parseByte() 将二进制字符串解析为符号大小(符号和大小),这里应该解析为有符号二进制(2 的补码,即 MSB 是符号位)).

where parseByte() parses the binary string as a sign-magnitude (the sign and the magnitude), where it should parse as a signed binary (2's complement, i.e. MSB is the sign-bit).

我错了吗?

推荐答案

我错了吗?

是的.Javadoc 没有提及 2 的补码.事实上,它明确说明了它如何识别负值(即 - 前缀,因此有效地人类可读"的符号大小).

Yes. The Javadoc says nothing about 2's-complement. Indeed, it explicitly states how it recognises negative values (i.e. a - prefix, so effectively "human-readable" sign-magnitude).

换个角度想想.如果 parseByte 将 radix-2 解释为 2 的补码,您希望它为 radix-10(或者实际上,任何其他基数)做什么?为了一致性,它必须是 10 的补码,这会很不方便,我可以向你保证!

Think about it another way. If parseByte interpreted radix-2 as 2's-complement, what would you want it to do for radix-10 (or indeed, any other radix)? For consistency, it would have to be 10's-complement, which would be inconvenient, I can assure you!

这篇关于Wrapper 的 parseXXX() 用于有符号二进制误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆