-
Notifications
You must be signed in to change notification settings - Fork 4
Binary Huffman Coding
Anthony Christe edited this page Dec 3, 2013
·
12 revisions
- Create an instance of a FileInputStream with the file name passed into constructor
- Pass the FileInputStream to the constructor of the BufferedInputStream
- 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
- 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).
- Java handles bytes in odd ways, often times converting them to ints when you least expect it
- Make sure you cast all byte literals (i.e. 0xE8 -> (byte) 0xE8)
- Make sure all operations involving bytes use the magic & 0xFF
- Java integers are 32 bits
- Each byte is 8 bits
- Therefore, 4 bytes exactly fit into 1 integer
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
- ByteBuffer API
- [ByteBuffer.wrap(byte[] array)](http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#wrap(byte[]\)) - Returns an instance of a ByteBuffer given an array of bytes
- [ByteBuffer.getInt()](http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(\)) - Returns the integer value of an instance of a ByteBuffer
- 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
- 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

