我只能大概记得当时面试的题目啦。
1.将offset(取0~7)位设置为bitvalue(0或1).private byte setBit(byte value,int offset,int bitValue){
    if(bitValue==0)
    return (byte)(value.&~((<<offset));
else return............;填空。(在处填空。)
}
3.有一个byte数组,里面有些包,包头0x00,0x11,包尾0x00,0x22
(包中也可能有0x00,0x22)实现下面的方法:
int getPackCount(byte[] data,int n)
求取长度为n的data字节数组中,有多少个这样的包?

解决方案 »

  1.   

    写了有一会了,不常处理byte。没ide答不出来这题。
    public static void main(String[] args) {
    byte value = (byte) (125 & 0XFF);
    System.out.println(Integer.toBinaryString(value));
    int rs = setBit(value, 0, 0) & 0XFF;
    System.out.println(Integer.toBinaryString(rs));
    } private static byte setBit(byte value, int offset, int bitValue) {
    int[] tmp = new int[] { 1, 1, 1, 1, 1, 1, 1, 1 };
    tmp[offset] = bitValue;
    String t = "";
    for (int i = 0; i < 8; i++)
    t = tmp[i] + t;
    int a = Integer.parseInt(t, 2) & 0XFF;
    return (byte) ((value & a) & 0XFF);
    }
      

  2.   

    http://blog.csdn.net/sunyujia/archive/2008/05/04/2385727.aspx 
    http://topic.csdn.net/u/20081013/20/cf4c88cf-a314-4343-a77b-4bd50477df2e.html第2题一会换换脑子回来在看。
      

  3.   

    第一个:
    public class BitOpt { public static byte setBit(byte value, int offset, int bitValue) {
    if (bitValue == 0) return (byte)(value & ~(1 << offset));
    else return (byte)(value | (1 << offset));
    } public static void main(String[] args) {
    byte b = 101;
    System.out.println(Integer.toString(b, 2));
    b = (byte) setBit(b, 2, 0);
    System.out.println(Integer.toString(b, 2));
    b = (byte) setBit(b, 4, 1);
    System.out.println(Integer.toString(b, 2));
    }}
      

  4.   

    第二个:楼下请再帮我多拿几组数据测试一下
    public class BitOpt { public static int getPackCount(byte[] data, int n) {
    if (data == null || data.length == 0 || n <= 0) return 0;
    final byte PACKHEAD1 = 0x00;
    final byte PACKHEAD2 = 0x11;
    final byte PACKTAIL1 = 0x00;
    final byte PACKTAIL2 = 0x22;
    int count = 0;
    final int toidx = Math.min(data.length, n) - 1;
    boolean flag = false;
    for (int i = 0; i < toidx;) {
    if (flag) {
    if (data[i++] == PACKTAIL1 && data[i++] == PACKTAIL2) {
    count++;
    flag = false;
    }
    } else {
    if (data[i++] == PACKHEAD1 && data[i++] == PACKHEAD2) {
    flag = true;
    }
    }
    }
    return count;
    } public static void main(String[] args) {
    byte[] td = {
    0x12, 0x00, 0x69, 0x00, 0x11, 0x09, 0x00, 0x14,
    0x00, 0x22, 0x00, 0x65, 0x22, 0x11, 0x00, 0x11,
    0x00, 0x22, 0x12
    };
    System.out.println(getPackCount(null, 23));
    System.out.println(getPackCount(td, 0));
    System.out.println(getPackCount(td, -1));
    System.out.println(getPackCount(new byte[0], 23));
    System.out.println(getPackCount(td, 23));
    }}