in reply to unpacking 6-bit values
Update 3: I can't make pack & unpack work. I think endianness is biting me. A simple conversion of the C program to perl works, but isn't as nice to use as pack/unpack would have been. My best perl attempt so far is:
# Roboticus' second attempt my $robo_2 = sub { my @orig = unpack "S*", shift; my $bits=0; my $buf=0; my @bytes; while (@orig) { $buf |= (shift @orig)<<$bits; $bits += 16; while ($bits>6) { push @bytes, $buf & 0x3f; $buf>>=6; $bits-=6; } } push @bytes, $buf if $bits; return (@bytes); };
When I was looking at pack trying to find a way to efficiently do the task, I noticed that it has a u flag for uuencoding! So just use that to do the job. You'll have to set the "length of data" byte at the front, but that should be trivial.
roboticus@Boink:~ $ cat 876421.pl #!/usr/bin/perl use strict; use warnings; my $orig = "Now is the time for all "; my $enc = pack "u", $orig; print "$enc\n"; my $dec = unpack "u", $enc; print "$dec\n"; my (undef, @bytes) = map { 0x3f & ord($_) } split //, $enc; printf "%02x ", $_ for @bytes; roboticus@Boink:~ $ perl 876421.pl 83F]W(&ES('1H92!T:6UE(&9O<B!A;&P@ Now is the time for all 33 06 1d 17 28 26 05 13 28 27 31 08 39 32 21 14 3a 36 15 05 28 26 39 0 +f 3c 02 21 01 3b 26 10 00 0a
...roboticus
When your only tool is a hammer, all problems look like your thumb.
UPDATE: The reason I was looking into pack was that I had a better C program that I thought might translate into a quick perl script. The newer C program is:
#include <stdio.h> unsigned char inbuf[]="Now is the time for all "; unsigned char outbuf[50]; void hexdump(unsigned char *p, int n) { for (int i=0; i<n; i++) { printf("%02x ", *p++); } puts("\n"); } int main(int, char **) { unsigned char *src = inbuf; unsigned char *srcEnd = src + sizeof(inbuf); unsigned char *dst = outbuf; hexdump(src, sizeof(inbuf)); int bits = 0; int buf = 0; while (src != srcEnd) { buf |= (*src++)<<bits; bits += 8; while (bits > 6) { *dst++ = buf & 0x3f; buf >>= 6; bits -= 6; } } hexdump(outbuf, dst-outbuf); }
Update 2: I forgot to remove the top two bits of the bytes to give you the values you wanted, and I also stripped out the first byte. To do so, I added the last two lines to the code (above) and I added the last line of output (above). Of course, now with the overhead of splitting the string back into individual characters, and transforming the bytes after the map may quite likely make the uuencoded version slower than some of the alternatives. Ah, well.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: unpacking 6-bit values
by BrowserUk (Patriarch) on Dec 10, 2010 at 15:19 UTC | |
by roboticus (Chancellor) on Dec 10, 2010 at 22:52 UTC | |
by BrowserUk (Patriarch) on Dec 11, 2010 at 08:07 UTC |