byte数组转为String的问题

wudeaaa 2010-03-02 12:55:43

import java.io.UnsupportedEncodingException;

public class Byte2String {

public static void main(String args[]) throws UnsupportedEncodingException {
bytetochar();
}

public static void bytetochar() throws UnsupportedEncodingException {
byte addr[] = new byte[] {
(byte) 192, (byte) 168, (byte) 0, (byte) 1};
StringBuffer buff = new StringBuffer();
for (int j = 0; j < addr.length; j++){
buff.append(addr[j] + ".");

}
String sip = buff.toString();
System.out.println(sip);

}
}
希望输出192.168.0.1,却输出-64.-88.0.1.
...全文
1052 14 打赏 收藏 转发到动态 举报
写回复
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
truediego 2010-03-02
  • 打赏
  • 举报
回复
你把"192.168.0.1".getBytes()打出来,就知道为什么了
liguang168 2010-03-02
  • 打赏
  • 举报
回复
引用 11 楼 orangemike 的回复:
buff.append((addr[j] & 0xff)+".");


========================================
麻烦同志。如果把“.”放在后面,你什么时候删除?
放在前面最好。buff.substring(1);
看清楚再回复好吗?
mirroy 2010-03-02
  • 打赏
  • 举报
回复
java爱好者的免费学习视频、实战视频

下载列表 参见博客

http://user.qzone.qq.com/312311285/blog/1264432325
orangemike 2010-03-02
  • 打赏
  • 举报
回复
buff.append((addr[j] & 0xff)+".");
liguang168 2010-03-02
  • 打赏
  • 举报
回复
引用 8 楼 paodan 的回复:
Java codepublicstaticvoid byte2int() {byte addr[]=newbyte[] {
(byte)192, (byte)168, (byte)0, (byte)1
};
String s="";for (int j=0; j< addr.length; j++) {int a= addr[j];i?-


====================================
不需要这样麻烦吧。呵呵。
liguang168 2010-03-02
  • 打赏
  • 举报
回复
public static void bytetochar()
{
byte addr[] = new byte[]
{ (byte) 192, (byte) 168, (byte) 0, (byte) 1 };
StringBuffer buff = new StringBuffer();
for (int j = 0; j < addr.length; j++)
{
buff.append("." + (addr[j] & 0xff));
}
String sip = buff.substring(1);
System.out.println(sip);
}
paodan 2010-03-02
  • 打赏
  • 举报
回复

public static void byte2int() {
byte addr[] = new byte[] {
(byte) 192, (byte) 168, (byte) 0, (byte) 1
};
String s = "";
for (int j = 0; j < addr.length; j++) {
int a = addr[j];
if (a < 0) {
a = 256 + a;
}
s += a + ".";

}
System.out.println(s);

}
bbb332 2010-03-02
  • 打赏
  • 举报
回复
byte的范围是-128到127,127+1=-128,依次类推127+(192-127)=-64,127+(168-127)=-88
wudeaaa 2010-03-02
  • 打赏
  • 举报
回复
引用 3 楼 luffysy 的回复:
(byte) 192, (byte) 168  超过byte范围了
这是程序的需要,
Z_FEI 2010-03-02
  • 打赏
  • 举报
回复
byte addr[] = new byte[] {
(byte) 192, (byte) 168, (byte) 0, (byte) 1};
这句话已经把超出byte范围的值强制转换了
Z_FEI 2010-03-02
  • 打赏
  • 举报
回复
byte addr[] = new byte[] {
(byte) 192, (byte) 168, (byte) 0, (byte) 1};
这句话已经将超出byte范围的值强制转换了
LuffySY 2010-03-02
  • 打赏
  • 举报
回复
(byte) 192, (byte) 168 超过byte范围了
princess_rosie 2010-03-02
  • 打赏
  • 举报
回复
byte 是一个字节的, 它的取值范围很小,你前两个下标都超出了它的取值范围,所以输出异常,后两个下标正常,所以输出正常 要不改成char[] addr=new char[]; 这个是字符型的

两个各有所长,也都有缺陷,有谨慎使用
相关推荐

62,566

社区成员

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