I’m currently trying to build a lookup table for a huffman tree using a pretty simple preorder traversal algorithm, but I’m getting stuck carrying out very basic bit wise operations. The psuedo code follows:
void preOrder(huffNode *node, int bit) //not sure how to represent bit
{
if (node == NULL)
return;
(1) bit = bit + 0; //I basically want to add a 0 onto this number (01 would go to 010)
preOrder(node->getLeft(), bit);
(2) bit = bit - 0 + 1; //This should subtract the last 0 and add a 1 (010 would go to 011)
preOrder(node->getRight());
}
I’m getting quite confused about how to carry out the operations defined on lines (1) and (2)
What data type type does one use to represent and print binary numbers? In the above example I have the number represented as an int, but i’m pretty sure that that is incorrect. Also how do you add or subtract values? I understand how & and | types logic works, but I’m getting confused as to how one carries out these sorts of operations in code.
Could anyone post some very simple examples?
Here’s some basic examples of binary operations. I’ve used mostly in-place operations here.
If you want to print a binary number you need to do it yourself… Here’s one slightly inefficient, but moderately readable, way to do it:
[edit] If I wanted faster code, I might pre-generate (or hardcode) a lookup table with the 8-bit sequences for all numbers from 0-255.
Instead, you could do this:
Or just unroll the whole thing. 😉
Of course, those 8 bytes in the lookup are the same length as a 64-bit integer… So what about this? Much faster than all that pointless meandering through character arrays.
Naturally, in the above code you would represent your lookup values as int64 instead of strings.
Anyway, just pointing out that you can write it however is appropriate for your purposes. If you need to optimize, things get fun, but for most practical applications such optimizations are negligible or pointless.