Help with my compression code
Lengthy code... appreciate some help though.
My compressed files are much larger than the originals are, by several times. The classes not shown in the code are from Shaffer's Data Structures and Algorithms for Java, and they are known to work. The problem comes when I print out the codeTable to the beginning of the encoded file (it's HUGE!) and the "compressed" files are even larger without the codeTable output to it. The problem comes since the bit representations of the Huffman tree are printed as bytes. So far only the compression portion is implemented, not decompressing.
I would appreciate if someone had a few minutes to kill and could help me out here. I believe the code is fairly well strcutured and easy to follow.
Thanks.
import java.io.*;
import java.util.*;
public class HuffZip {
private static String[] codeTable = new String[256]; // The code lookup table
private static int[] freqTable = new int[256]; // The frequencies of bytes
private static int total = 0; // Total number of bits needed by the Huffman code of a file
private static List hufflist = null; // Initial List of HuffTree nodes
private static HuffTree tree = null; // The HuffTree
private static String inf; // The name of the input file
private static String ouf; // The name of the output file
private static File inF; // Input File
private static File ouF; // Output File
private static BufferedInputStream ins;
private static BufferedOutputStream ous;
static void usage() { // Called when args not proper length or format
System.out.println("\"Usage: java HuffZip <zip|unzip> <inputFile> <outputFile>\"");
System.exit(0);
} // method Usage
static void HZip(BufferedInputStream ins, BufferedOutputStream ous, List hufflist) throws IOException {
int c;
String tempString;
int tempInt;
int i;
int freq;
byte letter; // byte letter;
HuffTree temptree;
while ((c = ins.read()) != -1) {
tempString = String.valueOf(c);
tempInt = Integer.parseInt(tempString);
freqTable[tempInt] += 1;
} // while
for (i = 0; i < freqTable.length; i++)
char temp = (char)i;
System.out.println(temp);
letter = ((byte)temp);
if((int)letter < 0)
letter += 256;
// if ( (0xff & letter) < 0) // Something to do with this
// letter += 256;
freq = freqTable;
// System.out.println(letter + ", " + freq); // Need to fix the negative bytes // Testing
temptree = new HuffTree(new LettFreq(freq, letter));
for (hufflist.setFirst(); hufflist.isInList(); hufflist.next())
if (temptree.weight() <= ((HuffTree)hufflist.currValue()).weight())
hufflist.insert(temptree);
break;
} // if
if (!hufflist.isInList())
hufflist.append(temptree);
} // for
// hufflist.print(); // Testing
} // method HZip
static void HUnzip(BufferedInputStream ins, BufferedOutputStream ous) throws IOException {
} // method HUnzip
static HuffTree buildTree(List hufflist) {
HuffTree temp1, temp2, temp3;
LettFreq tempnode;
for (hufflist.setPos(1); hufflist.isInList(); hufflist.setPos(1)) {
// While at least 2 items left
hufflist.setFirst();
temp1 = (HuffTree)hufflist.remove();
temp2 = (HuffTree)hufflist.remove();
tempnode = new LettFreq(temp1.weight() + temp2.weight());
temp3 = new HuffTree(tempnode, temp1, temp2);
// Return the list in sorted order
for (hufflist.setFirst(); hufflist.isInList(); hufflist.next())
if (temp3.weight() <= ((HuffTree)(hufflist.currValue())).weight())
hufflist.insert(temp3);
break;
} // Put in list
if (!hufflist.isInList()) // It is the heaviest value
hufflist.append(temp3);
} // for loop
hufflist.setFirst(); // Tree now only element on list
return (HuffTree)hufflist.remove(); // Return the tree
} // method buildTree
static void outputTree(BinNode node, String prefix) {
Assert.notNull(node, "Bad Input Tree");
// This is a full binary tree so must not be null subtrees
if (node.isLeaf()) {
// System.out.println(((LettFreq)node.element()).letter() + "\t" + prefix); // Testing
int byteCheck = (int)((LettFreq)node.element()).letter();
if (byteCheck < 0)
byteCheck = byteCheck + 256;
codeTable[byteCheck] = prefix;
total += prefix.length() * ((LettFreq)node.element()).weight();
// System.out.println(total); // Testing
// System.out.println(codeTable[byteCheck] + " " + prefix); // Testing
else {
outputTree(node.left(), prefix + "0");
outputTree(node.right(), prefix + "1");
static void encode(BufferedInputStream ins, BufferedOutputStream ous, HuffTree tree) throws IOException {
BinNode temp;
String line;
int i;
int c;
String tempString;
String s;
int tempInt;
for(i = 0; i < 256; i++)
ous.write(codeTable[i].getBytes());
while ((c = ins.read()) != -1) {
tempString = String.valueOf(c);
tempInt = Integer.parseInt(tempString);
s = codeTable[tempInt];
//System.out.println(s); // Testing
ous.write(s.getBytes());
} // while
} //method encode
public static void main(String args[]) throws FileNotFoundException, IOException {
String ext;
hufflist = new LList();
if (args.length != 3)
usage();
inF = new File(args[1]);
ouF = new File(args[2]);
ins = new BufferedInputStream(new FileInputStream(inF));
ous = new BufferedOutputStream(new FileOutputStream(ouF));
inf = args[1];
ouf = args[2];
HZip(ins, ous, hufflist);
HuffTree tree = buildTree(hufflist);
outputTree(tree.root(), "");
System.out.println("Average code length is: " + (double)total/(double)tree.weight()); // Testing
ins = new BufferedInputStream(new FileInputStream(inF)); // Reset input file
encode(ins, ous, tree);
// Close streams prior to program ending
ins.close();
ous.close();
} // method Main
} // class HuffZip
Downloading eclipse right now, thanks. I useJCreator
now, which is pretty lightweight and the onlyoutput
it provides is the compiler's textual messages.
I see where the problem is lying, however. 2places:
My huffman tree contains codes that seem to be upto
a few hundred bytes in length, hardly a savingsover
the single byte that represents a character!That's because your storing your bits as char's in
your strings. You should be storing your bits as
bits in a byte array. This will require some
knowledge of bit fiddling.Would you happen to know a place I could find a tutorial? I'd look myself, but not certain as to what I would be searching for (by name).
kudos.
Similar Messages
-
Need help with a activation code for Adobe Acrobat X Standard for my PC, Don't have older Version of Adobe Acrobat 9, 8 or 7.
You don't need to install the older version, you only need the serial number from your original purchase. If you don't have them to hand, did you register? If so, they should be in your Adobe account. If not you really need to contact Adobe, though it isn't clear they will be able to do anything without some proof of purchase etc.
-
Purchased DVD in US for Cdn viewing. Digital download will not work in Cda or US? please help with new Digital code that will work
You will need to contact the movie studio that produced the DVD and ask if they can issue you a new code valid for Canada. Apple cannot help you, and everyone here in these forums is just a fellow user.
Regards. -
Need help with adjusting Javascript code to work in Adobe Edge (Countdown)
Hello
Im a newbie when it comes to working with Javascript and Adobe Edge and need a bit of help with adjusting some javascript code to work with Adobe Edge. A friend of mine helped me with making this javascript code: Edit fiddle - JSFiddle
Its a simple countdown which counts down to a certain time at a certain date. What I aim to do is to add this code as a trigger on a text-element called "countdown" (within a symbol called "count").
I have tried to do this as the code is, but it does not work. Anyone have any suggestions?
Thanks!
Mvh,
Øyvind HermansHello again
I have stumbled upon a problem with these animations; They crash the browser after viewing them a little while, usually less than 30 seconds in.
Is this problem also occuring when you watch the animations?
Is the countdown-code to much for the browsers to handle?
Thanks in advance for your answers.
Sincerely,
Øyvind Hermans -
I need help on some HTML code if at all possible.
What I am trying to do is set up a page that someone can
enter their name address and email into a form and when they hit
the submit button it automatically sends them a premade email of my
choosing that I make prior and somehow maybe embeded into the html
code to the address that they entered? I dont know if it is
possible but I am sure it can be.
Thank you in advanceActually, you could be subject to "abuse complaints", not
"abuse".
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.dreamweavermx-templates.com
- Template Triage!
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
http://www.macromedia.com/support/search/
- Macromedia (MM) Technotes
==================
"bregent" <[email protected]> wrote in
message
news:fb547q$b49$[email protected]..
> >What I am trying to do is set up a page that someone
can enter their name
> address
>
> Sure, you can do it fairly easily with any scripting
language. You need to
> be
> cautious about sending automated emails to anyone
without first validating
> that
> they are the actual owners of the email address,
otherwise you open your
> site
> up to abuse.
>
> >I dont know if it is possible but I am sure it can
be.
>
> Huh?
> -
Need Help With Simple ABAP Code
Hello,
I'm loading data from a DSO (ZDTBMAJ) to an Infocube (ZCBRAD06). I need help with ABAP code to some of the logic in Start Routine. DSO has 2 fields: ZOCTDLINX & ZOCBRDMAJ.
1. Need to populate ZOCPRODCD & ZOCREFNUM fields in Infocube:
Logic:-
Lookup /BI0/PMATERIAL, if /BIC/ZOCBRDMAJ = /BIC/OIZOCBRDMAJ
then /BIC/ZOCPRODCD = ZOCPRODCD in Infocube
/BIC/ZOCREFNUM = ZOCREFNUM in Infocube
2. Need to populate 0G_CWWTER field in Infocube:
Logic:
Lookup /BIC/PZOCTDLINX, if /BIC/ZOCTDLINX = BIC/OIZOCTDLINX
then G_CWWTER = 0G_CWWTER in Infocube.
I would need to read single row at a time.
Thanks!I resolved it.
-
Would like help with treeset ,the codes that using for sorting, please ?
hi every body. i faced a problem while writing this program, everything worked properly except this one. The program is related to Jframe and it asks the user to add three labels , three text field , one text area and three Jbuttons which are add sort and exit. i could deal with add and exit but sort, i couldn't do it properly because i don't know the codes that should be added in actionperfomed?
These codes are :
package gui;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import sun.misc.Sort;
import domain.Student;
public class StudentFrame extends JFrame {
* This method initializes btnAdd
* @return javax.swing.JButton
private JButton getBtnAdd() {
if (btnAdd == null) {
btnAdd = new JButton();
btnAdd.setBounds(new Rectangle(13, 135, 59, 27));
btnAdd.setText("Add");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
btnAddClicked(); // TODO Auto-generated Event stub actionPerformed()
return btnAdd;
protected void btnAddClicked() {
// TODO Auto-generated method stub
String name = txtName.getText();
String id = txtID.getText();
String age = txtAge.getText();
Student s = new Student(name , id , age);
txtArea.setText(String.valueOf(s ));
* This method initializes btnSort
* @return javax.swing.JButton
private JButton getBtnSort() {
if (btnSort == null) {
btnSort = new JButton();
btnSort.setBounds(new Rectangle(95, 136, 62, 25));
btnSort.setText("Sort");
btnSort.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
btnSortClicked(); // TODO Auto-generated Event stub actionPerformed()
return btnSort;
protected void btnSortClicked() {
// TODO Auto-generated method stub
* This method initializes btnExit
* @return javax.swing.JButton
private JButton getBtnExit() {
if (btnExit == null) {
btnExit = new JButton();
btnExit.setBounds(new Rectangle(173, 134, 61, 23));
btnExit.setText("Exit");
btnExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.exit(0); // TODO Auto-generated Event stub actionPerformed()
return btnExit;
* This method initializes txtName
* @return javax.swing.JTextField
private JTextField getTxtName() {
if (txtName == null) {
txtName = new JTextField();
txtName.setBounds(new Rectangle(79, 11, 60, 23));
return txtName;
* This method initializes txtID
* @return javax.swing.JTextField
private JTextField getTxtID() {
if (txtID == null) {
txtID = new JTextField();
txtID.setBounds(new Rectangle(73, 55, 65, 26));
return txtID;
* This method initializes txtAge
* @return javax.swing.JTextField
private JTextField getTxtAge() {
if (txtAge == null) {
txtAge = new JTextField();
txtAge.setBounds(new Rectangle(74, 96, 61, 24));
return txtAge;
* This method initializes txtArea
* @return javax.swing.JTextArea
private JTextArea getTxtArea() {
if (txtArea == null) {
txtArea = new JTextArea();
txtArea.setBounds(new Rectangle(138, 5, 154, 128));
return txtArea;
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
StudentFrame thisClass = new StudentFrame();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
* This is the default constructor
public StudentFrame() {
super();
initialize();
* This method initializes this
* @return void
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
return jContentPane;
}Edited by: hypocrisy on Apr 26, 2009 6:51 PMThere are three actionPerformed in that program.One for add Jbutton , Sort , and Exit
the codes that i have added for add button after action performed are
String name = txtName.getText();
String id = txtID.getText();
String age = txtAge.getText();
Student s = new Student ( name , id , age);
System.out.println(s);
the codes for Exit button to make it works properly was :
System.out.println(0);
But when i came to Sort Button and i tried to enter many codes but it didn't sort properly so would you like to help me with the right codes :) -
Help with basic ABAP code (merge internal tables, sort of...)
Hello,
Can someone please help write some basic code for a Basis guy with limited ABAP knowledge?
Should be some easy points for an experienced ABAPer!
I have identicaly structured internal tables I_A and I_B and I_C which have already been filled by function models I called.
How will I code the following?:
I want to read all the data of I_A into a new internal table I_MASTER (structured the same as I_A,I_B and I_C).
Then I want to read I_B and:
1)Update I_MASTER with NEW records
2)Update existing records if the value of field MYFIELD in I_B is smaller than the value of MYFIELD in I_MASTER.
Then I want to read I_C and:
1)Update I_MASTER with NEW records
2)Update existing records if the value of field MYFIELD in I_C is smaller than the value of MYFIELD in I_MASTER.
Let me know if I can provide anymore information.
Thanks in advance for you help!
Adriaan
Message was edited by: Adriaan
Message was edited by: AdriaanHi Adriaan ,
I want to read all the data of I_A into a new internal table I_MASTER (structured the same as I_A,I_B and I_C).
<b>i_master[] = i_a[] .</b>
loop at i_b .
read table i_master with key myfiled < i_b-myfield .
if sy-subrc = 0 .
append i_master from i_b .
endif.
endloop.
loop at i_c .
read table i_master with key myfiled < i_c-myfield .
if sy-subrc = 0 .
append i_master from i_c .
endif.
endloop.
Let me know if this helped .
Regards,
Varun .
Message was edited by: varun sonu -
Hello, I am new to java and I need a bit of help with some code that I'm writing. here is the code:
import javax.swing.*;
public class Test{
public static void main(String[] args){
JOptionPane.showMessageDialog(null,"We will now build a block with *'s","Block",1);
String input=JOptionPane.showInputDialog(null,"Type a number: ","Number",3);
int number=Integer.parseInt(input);
int count=0; int count2=0;
for(count2=0; count2<number; count2++){
for(count=0; count<number; count++){
System.out.print("* ");
System.exit(0);
}Now, all I need is to build a block of *'s with the number that the user inputs. With the code that I wrote I get the correct number of *'s but not in the form of a block. They just print out in a straight line. I know this is a very simple task but could someone please help me out? What do I need to modify in my code so that the *'s print out arranged as a block like so:
**********Your code only uses the print method which prints without a carriage return/line feed. So you need to add a line of code to print a carriage return/line feed. Where? well that is your task to work out.
-
I just purchased a 7290 that was supposed to be unlocked (apparently it is refurbished). It came from cingular originally. My carrier can't unlock it to work with their system. Can anyone help me with free unlock codes?
Only your carrier can provide free unlock codes.
If you contact Horizon below in my signature, they do so cheaply and reliably.
1. If any post helps you please click the below the post(s) that helped you.
2. Please resolve your thread by marking the post "Solution?" which solved it for you!
3. Install free BlackBerry Protect today for backups of contacts and data.
4. Guide to Unlocking your BlackBerry & Unlock Codes
Join our BBM Channels (Beta)
BlackBerry Support Forums Channel
PIN: C0001B7B4 Display/Scan Bar Code
Knowledge Base Updates
PIN: C0005A9AA Display/Scan Bar Code -
Help with new error code (-1)!
Hi I am trying to update my iphone 4 to ios5. When it comes to the last stage, it shows this error of -1. I am unable to find any info related to this error code. Any help with this is highly appreciated! Many Thanks. Now the phone is unusable. Previously it showed several errors including 1600 series and they are all resolved. This is the last hudrle. Please Help!
ThanksLike many I experienced some issues when updating to iOS 5 (on launch day). I finally gave up on the Update option and chose the Restore option.
iOS 5 downloaded and installed without issue. I restored from Back Up and everything was in place. No errors.
If you are updating, try using Restore instead. -
Hi there can you help with this error code Oxc5d1281
I refilled the HP cartridges in my Photosmart C 7250 All-in-One and put them in and got this error. I have D/C power,etc and it still comes up with this error code. Now what?
Cheers,
British_ehHi british_eh
You could try resetting the printer, details here
Note though that the reliability of refills tends not be as good as originals, links below FYI.....
http://h10025.www1.hp.com/ewfrf/wc/document?docname=c00853819&cc=us&dlc=en&lc=en&jumpid=reg_R1002_US...
http://www.qualitylogic.com/2009HPinktest.pdf
Kind Regards, Ciara
Although I am an HP employee, I am speaking for myself and not for HP.
Twitter: @Ciara_B_HP -
Help with receiving compressed network data
I'm trying to send some compressed data over a network connection from a server (written in C) to my Java program. My server sends the length of the compressed data (in bytes) as a regular integer, then sends the compressed data itself. Therefore, my client is essentially this:
open Socket
while (true) {
read an int from the socket, using a DataInputStream object
allocate new byte array using the size provided above
read bytes from socket, using the DataInputStream object
decompress bytes, using an Inflater object
parse decompressed data
But prior to reading any compressed data, I have to do this:
while (dataIn.available() < amount_of_compressed_data) { ; }
where dataIn is my DataInputStream object, or else I get tons of zlib errors (header errors, data errors, internal stream errors) when I try to decompress my data. I thought that Sockets in Java were blocking though, and I shouldn't have had to do this. Can anyone explain?
Also, when I use an SSLSocket instead of a regular Socket, dataIn.available() always returns zero so my client is stuck in an infinite loop. I know the SSL handshake stuff has been set up properly because the client can send messages to the server which are handled correctly, so the problem isn't that. I know the bytes are being sent over the network from the server to the client because I can see them using Ethereal, but for some reason they never show up when calling available(). If I remove that call, I can read bytes from the SSLSocket but I get the zlib errors mentioned above. Does anyone know why this would be?
thanks in advance for any help.
- Danhi, thanks for your response.
Have you verified the order of the bytes in the int?
Are you sure that you are getting the correct length?
Different platforms can use different order for the
bytes in an in (little vs big endian). Are you
writing in network order?yes. The server calls htonl() before sending integers over the network, and I believe that using the DataInputStream class to read those integers will take care of byte order for me.
Read the documentation for available:
"Returns the number of bytes that can be read (or
skipped over) from this input stream without blocking
by the next caller of a method for this input stream.
The next caller might be the same thread or or
another thread.
The available method for class InputStream always
returns 0. "
It says one important thing. Streams can return zero.
They don't have to return a number which says how
many bytes there are available.
Kajoops. So if I remove the calls to available() because they don't do what I want, I get the data integrity exceptions I mentioned earlier. It seems to be a problem with my Inflater. It doesn't return the expected amount of uncompressed bytes (a value which the client will always know ahead of time), even though I'm passing it the correct amount of compressed bytes.
Here's the relevant portion of my code:
while (true) {
try {
DataInputStream dis = new DataInputStream(net_socket.getInputStream());
/* get size of compressed data */
int compressed_size = -1;
byte[] compressed_data = null;
// while (dis.available() < 4) { ; }
compressed_size = dis.readInt();
System.out.println("reading " + compressed_size + " bytes of compressed data");
compressed_data = new byte[compressed_size];
/* get compressed data */
// while (dis.available() < compressed_size) { ; }
dis.read(compressed_data, 0, compressed_size);
/* zlib header integrity check - should output 0x78, 0x9c */
System.out.println("0x" + Integer.toHexString(compressed_data[0]));
System.out.println("0x" + Integer.toHexString(compressed_data[1]));
/* uncompress data */
Inflater i = new Inflater();
byte[] uncompressed_data = new byte[PACKET_SIZE];
int uncompressed_size = -1;
i.reset();
i.setInput(compressed_data);
uncompressed_size = i.inflate(uncompressed_data);
System.out.println("received " + uncompressed_size + " bytes of uncompressed data");
/* consume data here */
catch (Exception e) {
e.printStackTrace();
}thanks again for any help.
- Dan -
Can anyone help with an Error Code 4450
I keep trying to burn cd's and everytime that I do, itunes cancels the disk burn and gives me the error code 4450. can anyone help out with this? thanks..
I am having the exact same problem! and now i can't access my pending downloads!! if anybody has any answers, i am begging you, please help me. if i can't fix this then i have wasted $40., so please, help me!
-
Help with some html code for flash site!
Got this site>
http:/www.thedesignport.com
Site works great! everything is uploaded! What I cant seem to
get workning is the html code to add a description under the title
of the website in a google search? Goto google enter "topanga
mountain school" I'm top spot on the second page but with NO
description?? have a look at the html code for
http://www.thedesignport.com
Have I gone wrong somewhere?? But I've found if you put
"topanga mountain school pdf" into google ( I have three pdf's on
the site) My site is Second on the search with a DESCRIPTION of the
pdf's under the site name?? I dont get it?? Any help would be
great!You're not getting any help here because this is the forum for discussions of the Community Help Client application and Help system in general. For CSS questions, you should probably try something like the Dreamweaver forum.
Maybe you are looking for
-
Does anyone know what's wrong with my C6380? The LCD display doesn't pop up when the printer starts. It just lay down all the times. Even I reset the printer with (press: Print Photos + Red Eye Removal), same thing happended. Does anyone has an idea?
-
Cant see my full view in edit window
Hi im new to mac and logic 9. In my edit window where you record your music, I cant see the full veiw of the edit window. I mean, at the top where you have the numbers on the ruler that makes up bars, I cant see the first bar. My view on the ruler in
-
I have a 0costarea characteristic. And it has authorisation object. I use this characteristic in two different reports. The question is how can i give a user different restriction for two report? For example in the A report 0costarea=100100,100101,10
-
Is there a way to have more than one SMTP server on iPod Mail?
The thread at this link http://tinyurl.com/5op2jn seems to indicate it's possible but there are no details provided. Can anyone help? Does anyone know if this could be a feature included in a future iPod Touch update?
-
Whatis the FileCatcher functionality in SAP WebDispatcher???
Hi all, the subject pretty much says it. What exactly is this FileCatcher and how does it work. I seem to be unable to find any information about it. Can someone point me in the right direction? Thanks in advance, Christian