netty工程,JAVA解析BCD码,BIN码

来源:互联网 发布:大二申请国外大学知乎 编辑:程序博客网 时间:2024/05/29 18:26

数据传递用NIO的ByteBuffer类型。

首先是BCD码转成JAVA的String 类型

这个是指定长度的

  public static final String readBCDWithLength(ByteBuffer byteBuffer,int count) throws IOException {    byte[] b = new byte[count];    byteBuffer.get(b);        return bcd2Str(b);    }
public static String bcd2Str(byte[] bytes) {StringBuffer temp = new StringBuffer(bytes.length * 2);      for (int i = 0; i <bytes.length; i++) {              temp.append((byte) ((bytes[i] & 0xf0) >>> 4));              temp.append((byte) (bytes[i] & 0x0f));          }          return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp                  .toString().substring(1) : temp.toString();      }

下面是BIN码的读取

一个Byte直接用byteBuffer.get();来读取。

指定长度的用下面的方法

    public static final byte[] readWithLength(ByteBuffer byteBuffer,int count) throws IOException {        byte[] b = new byte[count];    byteBuffer.get(b);                return b;    }
先读取成Byte数组,然后转成String

public static String getAscii(byte[] src) {int pos = -1;int len = src.length;for (int i = 0; i < len; i++) {if (src[i] == 0) {pos = i + 1;break;}if (src[i] < 0x20 || src[i] > 0x7e) {return " ";}}if (pos == -1) pos = len + 1;//return "";byte[] dest = new byte[pos - 1];System.arraycopy(src, 0, dest, 0, pos - 1);String s = new String(dest);s.trim();return s;}

如果是其他类型,直接强转就可以的。

如果对你有帮助,点个赞呗。

原创粉丝点击