Recently I have been trying to get my head around the PackBits compression algorithm and I'm having problems.

I understand that the packets consist of a one byte header followed by the given data and if the value of the header byte is positive, it is followed by the same number, n + 1 bytes of data.

However, I do not fully understand what happens if the header byte is negative?
If FF means repeat twice, FE means repeat 3 times and FD means repeat 4 times etc. What pattern does it follow? What would the header byte be if you needed to repeat the byte, say 20 times? Sorry if I'm missing the obvious.

I've been following this link thus far and apparently...

If this first byte is a negative number, the following data is packed and the number is a zero-based count of the number of times the data byte repeats when expanded. There is one data byte following the flag-counter byte in packed data; the byte after the data byte is the next flag-counter byte.

But I still don't understand how 'FE AA' is supposed to represent 3 bytes of the pattern 'AA'?

For a single byte in twos complement notation, FF is -1, FE is -2, FD is -3, etc. The values from 80 (-128) to FF (-1) are negative numbers. To get the positive values, do an "exclusive or" (xor / '^' operator) with FF, and then add one.

FD xor FF = 02. Add one and you get '03'. Therefore 'FD' = -3.

To get the number of repeats, get the "absolute value" of the signed byte, and then add one. [So if you're doing bitwise operations, you'll add one twice.]

To repeat 20 times, you need -19 decimal as a single-byte signed value. 19 decimal = 13 hex, xor FF = EC, + 1 = ED.

(P.S. To see if a number is negative, do 'and 80'. Zero result is positive; '80' result is negative. Or if you have signed bytes, as in Java or C, just check for '< 0' ;-)

Thank you so very much, that helped me out a heck of a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.