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

今天喝柠檬茶 2017-01-13 08:52:03
在第三版 的第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就会丢失导致的,请问怎么解决这个问题?
...全文
995 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
黎大 2017-01-14
  • 打赏
  • 举报
回复
这个没办法啊,byte就是0-127,你要是想转,就得把int拆成byte的运算 例如 [byte] = f(int) int 是 32位的,byte是八位的,也就是如果你不想出任何截断,那就准备好四个byte,至于怎么变,根据你的数据决定
今天喝柠檬茶 2017-01-14
  • 打赏
  • 举报
回复
引用 2 楼 peterlee1983 的回复:
这个没办法啊,byte就是0-127,你要是想转,就得把int拆成byte的运算 例如 [byte] = f(int) int 是 32位的,byte是八位的,也就是如果你不想出任何截断,那就准备好四个byte,至于怎么变,根据你的数据决定
谢谢了

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧