如何读字节从输入流取bit作位运算(JAVA实现)
在以下是笔者在遇到取bit位运算,源码如下: package com.bit; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; public class BitTest { byte[] content = {(byte)9,(byte)111,(byte)120,(byte)32}; public String readBitYear(byte[] bt) throws IOException { byte[] tmp = bt; byte a = new DataInputStream(new ByteArrayInputStream(tmp)).readByte();; //int aa = (a & 0xfc); int aa = a >>2<<2; aa += 2000; String year = Integer.toString(aa); return year; } public String readBitMoth(byte[] bt) throws IOException { byte[] tmp = bt; int b = (int)new DataInputStream(new ByteArrayInputStream(tmp)).readShort(); int bb = b & 0x03C0; bb = bb >> 6; String mon = Integer.toString(bb); while (mon.length()<2) { mon = "0"+mon; } return mon; } public String readBitDay(byte[] bt) throws IOException { byte[] tmp = bt; int c = (int)new DataInputStream(new ByteArrayInputStream(tmp)).readShort(); int cc = c & 0x003E; cc = cc >> 1; String day = Integer.toString(cc); while (day.length()<2) { day = "0"+day; } return day; } public String readBithour(byte[] bt) throws IOException { byte[] tmp = bt; DataInputStream tmp_dis = new DataInputStream(new ByteArrayInputStream(tmp)); tmp_dis.readByte(); int d1 = tmp_dis.readShort(); int dd = d1 & 0x1f0; dd = dd >> 4; String hour = Integer.toString(dd); while (hour.length()<2) { hour = "0"+hour; } return hour; } public String readBitmin(byte[] bt) throws IOException { byte[] tmp = bt; DataInputStream tmp_dis = new DataInputStream(new ByteArrayInputStream(tmp)); tmp_dis.readShort(); int e = tmp_dis.readShort(); int ee = e & 0xfc0; ee = ee >> 6; String min = Integer.toString(ee); while (min.length()<2) { min = "0"+min; } return min; } public String readBitsec(byte[] bt) throws IOException { byte[] tmp = bt; DataInputStream tmp_dis = new DataInputStream(new ByteArrayInputStream(tmp)); tmp_dis.readShort(); int f = tmp_dis.readShort(); int ff = f & 0x3f; String sec = Integer.toString(ff); while (sec.length()<2) { sec = "0"+sec; } return sec; } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BitTest bittest = new BitTest(); String year = bittest.readBitYear(bittest.content); String month = bittest.readBitMoth(bittest.content); String day = bittest.readBitDay(bittest.content); String hour = bittest.readBithour(bittest.content); String min = bittest.readBitmin(bittest.content); String sec = bittest.readBitsec(bittest.content); System.out.println("years :" + year); System.out.println("months :" + month); System.out.println("days :" + day); System.out.println("hours :" + hour); System.out.println("mins :" + min); System.out.println("secs :" + sec); }
上一篇:
IDEA上Java项目控制台中文乱码