包装的parseXXX()为符号二进制误解 [英] Wrapper's parseXXX() for signed binary misunderstanding

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

问题描述

让我们来的Byte.parseByte()作为一个例子作为包装中的一个 parseXXX()

从<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte%28java.lang.String,%20int%29\"相对=nofollow> parseByte(一个String,诠释基数)的JavaDoc的


  

将字符串参数作为由指定的基数中的一个符号字节
  第二个参数。


但是,这并不完全正确,如果基数= 2 。换句话说, -127 的二进制文字是千万

 字节B =(字节)0b10000000;

所以下面应该是真实的:

 字节B =的Byte.parseByte(10000000,2);

但不幸的是,它抛出 NumberFormatException异常,而是我必须这样做如下:

 字节B =的Byte.parseByte( -  111111,2);

其中, parseByte()解析二进制字符串作为一个符号 - 幅度(符号和幅度),它应该解析为一个有符号二进制(2的补数,即MSB为符号位)。

我错了这件事?


解决方案

  

我错了这件事?


是的。的Javadoc只字未提二进制补码。事实上,它明确指出它是如何识别负值(即 - preFIX,所以有效地人类可读的符号 - 幅度)。

想想另一种方式。如果 parseByte 间preTED基数-2作为二进制补码,你会想什么为基数10做(或实际上,任何其他基数)?为了保持一致性,它必须是10's补,这将是不方便,我可以向你保证!

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

From parseByte(String s, int radix)'s JavaDoc:

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

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);

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

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

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).

Am I wrong about this?

解决方案

Am I wrong about this?

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).

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!

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

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