双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

关于int转byte会丢失精度的问题

今天喝柠檬茶 今天喝柠檬茶 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在第三版 的第12章 555页,有行代码是输入一个ip地址,但是实际显示由于精度丢失,导致最后结果显示的是负数,请问怎么处理呢?
        JFormattedTextField ipField = new JFormattedTextField(ipFormatter);
ipField.setValue(new byte[] { (byte)(192), (byte)168, 4, 1 });
addRow("IP地址格式", ipField);

下面是实现ip输入的代码
        class IPAddressFormatter extends DefaultFormatter {
public String valueToString(Object value) throws ParseException {
if (!(value instanceof byte[])) {
throw new ParseException("该IP地址的值只能是字节数组", 0);
}
byte[] a = (byte[]) value;
if (a.length != 4) {
throw new ParseException("IP地址必须是四个整数", 0);
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 4; i++) {
int b = a[i];
if (b < 0)
b += 256;
builder.append(String.valueOf(b));
if (i < 3)
builder.append('.');
}
return builder.toString();
}

public Object stringToValue(String text) throws ParseException {
// 将格式化文本框内的字符串以点号(.)分成四节。
String[] nums = text.split("\\.");
if (nums.length != 4) {
throw new ParseException("IP地址必须是四个整数", 0);
}
byte[] a = new byte[4];
for (int i = 0; i < 4; i++) {
int b = 0;
try {
b = Integer.parseInt(nums[i]);
} catch (NumberFormatException e) {
throw new ParseException("IP地址必须是整数", 0);
}
if (b < 0 || b >= 256) {
throw new ParseException("IP地址值只能在0~255之间", 0);
}
a[i] = (byte) b;
}
return a;
}
}

按照书上说的,这样显示出来 前2位就是负数了,int转byte的时候超过127就会丢失导致的,请问怎么解决这个问题?
...全文
评论 3
收藏 已收藏
分享
返回顶部
今天喝柠檬茶
Java SE 62,621 成员 307,251 内容