日期:2014-05-20  浏览次数:20602 次

java中socket读取数据问题
调试助手发送数据fe fe fe 69
使用BufferedInputStream读取时,得到的字节数组中的数据是66 65 66 65 66 65 36 39,怎样才能得到fe fe fe 69
socket java

------解决方案--------------------
转一下字节
BufferedInputStream bf=new BufferedInputStream(fs);
FileOutputStream os=new FileOutputStream("e:/os.txt");
byte[] buffer = new byte[1024];   
int count = 0;  
while((count = bf.read(buffer)) >= 0){  
os.write(buffer, 0, count);
}
------解决方案--------------------
也可以直接使用DataInputStreamReader或BufferedReader等读取。
------解决方案--------------------
我着一个笨办法:

import java.util.Arrays;
public  class ByteArrayToHex{
    public static void main(String[] args){
        byte[] result;
        byte[] original = {0x66, 0x65, 0x66, 0x65, 0x66, 0x65, 0x36, 0x39};//字节数组中的数据,为16进制.
        result = change(original);
        System.out.println(Arrays.toString(result));//显示。
    }

    public static byte[] change(byte[] b){
        byte[] out = new byte[b.length/2];//定义返回数组的大小。
        byte h,l;                         //两个临时变量。
        for(int i=0; i<b.length; i+=2){
            if(b[i]>=97&&b[i]<=102){
                h = (byte)(b[i]-97+10);//把高位的ascii码,转成其代表的字符。a-f
            }else if(b[i]>=65 && b[i]<=69){
                h = (byte)(b[i]-65+10);//A-F.
            }else{
                h = (byte)(b[i]-48);//0-9
            }
    h = (byte)(h<<4);//左移4位,放在高位。

            if(b[i+1]>=97 && b[i+1]<=102){
                l = (byte)(b[i+1]-97+10);//把低位的ascii码,转成其代表的字符或数字。a-f
            }else if(b[i+1]>=65 && b[i+1]<=69){
                l = (byte)(b[i+1]-65+10);//(A-F).
            }else{
                l = (byte)(b[i+1]-48);//0-9
            }