2014-04-06 5 views
0

파일에서 17 비트 블록을 읽는 코드를 작성하려고하는데이 작업을 수행하는 방법을 모릅니다. crc 알고리즘을 적용하려면 다음 17 비트를 읽어야합니다.파일에서 특정 비트 수 가져 오기 Java

+0

당신이 17 비트를 표현하려면 어떻게; 하나의'int' 또는'byte [] ', 또는 다른 방법으로? –

+0

4 바이트를 가지고 있고 Int가 2 바이트 만 가지고 있기 때문에 17 비트가 필요하지만, 17 비트 만 선택할 생각이 없습니다. – Fabiman89

+0

아니요, Java에서는 'int'는 항상 32 비트를 가지고 있습니다. 그러나 그것은 서명 된 값입니다. Java의'short'는 16 비트입니다. –

답변

3

오늘 오후에 뭔가 프로그래밍을 느꼈습니다.

아래의 클래스 BitReaderreadBits 메서드를 통해 한 번에 최대 8 비트를 읽거나 readBits17 메서드를 통해 17 비트를 읽는 것을 허용합니다.

소스 코드

public class BitReader { 
    private static final int[] MASK = new int[16]; 
    static { 
     for (int i = 0; i < 16; i++) { 
      MASK[i] = (1 << i) - 1; 
     } 
    } 

    private InputStream in; 

    private int bitsLeft; 

    private int bitBuffer; 

    public BitReader(InputStream in) { 
     this.in = in; 
    } 

    /** 
    * Reads at most 8 bits from the InputStream. 
    * 
    * @param bits 
    *   between 1 and 8 (inclusive) 
    */ 
    public int readBits(int bits) throws IOException { 
     if (bits < 1 && bits > 8) 
      throw new IllegalArgumentException("bits"); 
     if (bits > bitsLeft) { 
      int r = in.read(); 
      if (r == -1) { 
       throw new EOFException(); 
      } 
      bitsLeft += 8; 
      bitBuffer = (bitBuffer << 8) | r; 
     } 
     int result = bitBuffer >> (bitsLeft - bits); 
     bitsLeft -= bits; 
     bitBuffer &= MASK[bitsLeft]; 
     return result; 
    } 

    public int readBits17() throws IOException { 
     return readBits(8) << 9 | readBits(8) << 1 | readBits(1); 
    } 
} 

클래스 TestBitReader를 사용하는 방법을 보여줍니다.

public class Test { 
    public static void main(String[] args) throws IOException { 
     // 1 00000010 01000011 = 65536 + 2 * 256 + 67 = 66115 
     // Creating a stream that repeats this number twice 
     // 10000001 00100001 1, 10000001 00100001 1 
     // 10000001 00100001 11000000 10010000 11[000000] = 129, 33, 192, 144, 192 
     byte[] data = { (byte) 129, 33, (byte) 192, (byte) 144, (byte) 192 }; 
     ByteArrayInputStream in = new ByteArrayInputStream(data); 
     BitReader br = new BitReader(in); 
     // Should print 66115, 66115, 0 
     System.out.println(br.readBits17()); 
     System.out.println(br.readBits17()); 
     System.out.println(br.readBits(6)); 
    } 
} 

(저작권 :. 그들이 맞는 볼 모든 사람이 사용할 수 있도록 본인은, 공개 도메인에이 코드를 삽입)

+0

감사합니다 !! 정말 좋은 직장, 고마워 !! – Fabiman89

관련 문제