代码如下;
public class Test2 {
private static void writeHexByte(OutputStream w, byte[] b) throws IOException {
for (int i = 0; i < b.length; i++) {
int temp1=(b[i] & 0xf0) >> 4;//byte转16进制
char temp11=bin2char(temp1);
int temp111=(int)temp11;
w.write(temp111);//获取高位
///////////////////////////////////
int temp2=b[i] & 0x0f;//byte转16进制
char temp22=bin2char(temp2);
int temp222=(int)temp22;
w.write(temp222);//获取低位
}
}
private static char bin2char(int bin) {
char c;
c=(char) (bin < 10 ? bin + '0' : bin - 10 + 'A');
return c;
} public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String str="1我";
File file=new File("d:"+File.separator+"temp.log");
OutputStream out=new FileOutputStream(file);
byte b[]=str.getBytes();
writeHexByte(out,b);//结果:输出到d:\temp.log 内容为31CED2
out.close();
}}
代码功能是把字符串的16进制写入到文本,我实在不明白的是c=(char) (bin < 10 ? bin + '0' : bin - 10 + 'A'); 这行代码?如何传入的大于10,为何是 bin - 10 + 'A'? 对于大于10,是中文的情况,请高手解答原理
public class Test2 {
private static void writeHexByte(OutputStream w, byte[] b) throws IOException {
for (int i = 0; i < b.length; i++) {
int temp1=(b[i] & 0xf0) >> 4;//byte转16进制
char temp11=bin2char(temp1);
int temp111=(int)temp11;
w.write(temp111);//获取高位
///////////////////////////////////
int temp2=b[i] & 0x0f;//byte转16进制
char temp22=bin2char(temp2);
int temp222=(int)temp22;
w.write(temp222);//获取低位
}
}
private static char bin2char(int bin) {
char c;
c=(char) (bin < 10 ? bin + '0' : bin - 10 + 'A');
return c;
} public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String str="1我";
File file=new File("d:"+File.separator+"temp.log");
OutputStream out=new FileOutputStream(file);
byte b[]=str.getBytes();
writeHexByte(out,b);//结果:输出到d:\temp.log 内容为31CED2
out.close();
}}
代码功能是把字符串的16进制写入到文本,我实在不明白的是c=(char) (bin < 10 ? bin + '0' : bin - 10 + 'A'); 这行代码?如何传入的大于10,为何是 bin - 10 + 'A'? 对于大于10,是中文的情况,请高手解答原理
然后16进制的10开始对应是A-F这个你应该知道吧.c=(char) (bin < 10 ? bin + '0' : bin - 10 + 'A'); 所以方法返回这里应该不难理解.