Skip to content

Binary Huffman Coding

Anthony Christe edited this page Dec 3, 2013 · 12 revisions

Reading in Binary Files

int read(byte[] b)
  • Attempts to read b.length bytes into b
  • Returns total number of bytes read or -1 if nothing was read
  • Need to know size of file beforehand
  • Useful in current assignment to read in first 4 bytes
int read()
  • Reads the next byte from the stream
  • Returns the byte value or -1 if the end of the stream has been reached
  • Easiest to set up a while loop and continually byte for -1 (similar to BufferedReader example in lab, except we're now checking for -1 instead of null).

Finding an integer from 4 bytes

  • Java integers are 32 bits
  • Each byte is 8 bits
  • Therefore, 4 bytes exactly fit into 1 integer

bytes in int

The Universal Way - Bit Shifting
let result = 0
let byte[] be an array of bytes

for index 0 to 3:
  shift result to left by 8 bits
  result = result BIT-OR (byte[index] BIT-AND 0xFF)

return result
The Java Way - ByteBuffer

Reading Bits

BitReader Object
  • Need an abstract way traverse bits from array of bytes
  • Create a BitReader class which takes an array of bytes and provides methods for traversing of bits
  • Easiest to read entire file into byte array and then extract individual bits from there
  • To find any particular bit, need to know which byte it is contained in and which index in the byte the bit is

bit-layout

  • For example, bit 19 is the 3rd bit in the 2nd byte, but how can we determine this?
  • Index into array = bit index / 8 (i.e. 19 / 8 = 2)
  • Index into byte = bit index % 8 (i.e. 19 % 8 = 3)
  • I might recommend the method get(int bitIndex) which returns the bit value from the BitReader
  • Or you could create an iterator which does the above behind the scenes, and iterates over bit values
Querying Specific Bits

Receiving the tree

Decoding the Message

Writing Result File

Padding with Zeros

Debugging

Printing a byte a string

Clone this wiki locally