Wrapper 的 parseXXX() 用于有符号二进制误解

编程入门 行业动态 更新时间:2024-10-26 20:27:18
本文介绍了Wrapper 的 parseXXX() 用于有符号二进制误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我们以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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 03:17:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/928380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:误解   符号   Wrapper   parseXXX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!