关于byte转为char的
数据库中是以number(1,0)存储的,其中只存储0-9数字。我从数据中取出来放在resultSet中想转化为char
(char)rst.getByte(2);
但取出的却是把数字对应的ASCII码对应的字符输出了
有什么办法把数字2(Byte)转为char型吗?
呵呵,我太小白了。有更简单的方法:
[code="java"]
byte source = 2;
char result = (""+source).charAt(0);
System.out.println(result);
[/code]
[color=blue][b]暂时没想到好的办法,自己写的,仅供参考:[/b][/color]
[code="java"]import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class IOTest {
public final static byte base = 0x30;
public static char ByteToChar(byte source) throws Exception {
if (source > 9 || source < 0)
throw new IllegalArgumentException("请输入0-9之间的数值");
PipedOutputStream out = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(out);
// 以字节的方式写入
out.write(source + base);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(pin));
// 以字符的方式读出
char[] temp = new char[1];
reader.read(temp, 0, 1);
reader.close();
return temp[0];
}
public static void main(String[] agrs) throws Exception {
char test01 = IOTest.ByteToChar((byte)2);
//char test01 = IOTest.ByteToChar((byte)21); // 转换错误
//char test01 = IOTest.ByteToChar((byte)-2); // 转换错误
System.out.println(test01);
}
}
[/code]
还有一种更简单的方法:
[code="java"]
public class Test2 {
public static void main(String[] args) {
//byte source = 0x31 ;
byte source = 49;
char result = (char)source;
System.out.println(result);
}
}
[/code]
16进制的31,或者10进制的49,对应char的' 1 '