1,用byte byt = Byte.valueOf("01010100",2),若01串的第一位是1(如10000011)就会报溢出错,是怎么回事?
2,我用如下代码,将01字符串转化为字节,并写入testing.bin文件
File file_1 = new File("testing.bin");
file_1.createNewFile();
FileOutputStream is = new FileOutputStream(file_1);
String[] ss= new String[3];
ss[1] = "01100011";
ss[2] = "00000000";
ss[0] = "00100010";
byte[] byt = new byte[3];
for(int i=0;i<3;i++)
{
byt[i] = Byte.valueOf(ss[i],2);
is.write(byt[i]);
}
然后用下面的代码从testing.bin中读取字节,转化为01字符串
File file_1 = new File("testing.bin");
FileInputStream os = new FileInputStream(file_1);
byte[] bb= new byte[3];
os.read(bb);
StringBuffer rr = new StringBuffer();
for(int j=0;j<3;j++)
{
String temp = Integer.toString((byte)bb[j],2);
rr.append(temp);
}
System.out.println(rr.toString());
但结果是10001011000110,也就是说只要原来的01字符串第一位是0或前几位都是0的,这些0就被删去了,怎么解决这个问题得到与原来一模一样的01字符串呢???
2,我用如下代码,将01字符串转化为字节,并写入testing.bin文件
File file_1 = new File("testing.bin");
file_1.createNewFile();
FileOutputStream is = new FileOutputStream(file_1);
String[] ss= new String[3];
ss[1] = "01100011";
ss[2] = "00000000";
ss[0] = "00100010";
byte[] byt = new byte[3];
for(int i=0;i<3;i++)
{
byt[i] = Byte.valueOf(ss[i],2);
is.write(byt[i]);
}
然后用下面的代码从testing.bin中读取字节,转化为01字符串
File file_1 = new File("testing.bin");
FileInputStream os = new FileInputStream(file_1);
byte[] bb= new byte[3];
os.read(bb);
StringBuffer rr = new StringBuffer();
for(int j=0;j<3;j++)
{
String temp = Integer.toString((byte)bb[j],2);
rr.append(temp);
}
System.out.println(rr.toString());
但结果是10001011000110,也就是说只要原来的01字符串第一位是0或前几位都是0的,这些0就被删去了,怎么解决这个问题得到与原来一模一样的01字符串呢???
throws NumberFormatException {
return new Byte(parseByte(s, radix));
}可以看到在该方法内部调用的其实是parseByte(s,redix)方法,再看看该方法的源代码: public static byte parseByte(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (byte)i;
}现在来看看你的代码, Byte.valueOf("10000011",2)方法会调用int i = Integer.parseInt("10000011", 2),这句代码执行后i的值为131,这个值超出了byte的最大值127,所以会提示Value out of range。
第二个String temp = Integer.toString((byte)bb[j],2);
rr.append(temp);试试String temp = Integer.toBinaryString(bb[j]);
rr.append(temp).append("-");
//String temp = Integer.toString((byte) bb[j], 2);
//String temp = Integer.toString(bb[j], 2);
String temp = Integer.toBinaryString(bb[j]);
int len = temp.length();
for(int i=0; i<8-len; i++) {
temp = "0" + temp;
}
rr.append(temp).append(" ");
}