[Dub-pm] Quick pack question.

Aidan Kehoe kehoea at parhasard.net
Wed Oct 13 08:17:06 CDT 2004

 Ar an triú lá déag de mí Deireadh Fómhair, scríobh Mcnamara John: 

 > Here is one way to do it (if I have understood correctly):

Hmm, thanks for that, but there's relatively little pack magic compared to
what I had a gut feeling, was possible. Ah well. Pack seems more oriented to
quanities greater than a byte.

I ended up doing it algorithmically; here's the PHP (don't look so shocked,
the Perl pack works fine in PHP, so asking here was relevant). If you read
it closely, you'll realise I didn't even pose the question here
properly. :-)

/* Take $input, which is a GSM-encoded string packed according to the 3G TS
   23.038 specifications section 6.1.2, and return a string where each octet
   corresponds to one and only one character, and no octet has the high bit
   set. */

function seven_bit_packed_to_octets($input)
	$from_array = preg_split('//', $input, -1, PREG_SPLIT_NO_EMPTY);
	$output = '';
	$count_from = count($from_array);

	/* Move through the octets in the input string. */ 
	for ($index = 0; $index < $count_from; ++$index) {

		/* We start taking seven bits from the current, none from the
		   previous, then take six from this, one from the previous,
		   then five from this, one from the previous. .. */
		$bits_from_previous = $index % 7;

		/* Can't use -1 as an array index, so we check that $index is
		   non-zero before taking the bits from the previous entry in
		   the array. */
		if (0 != $index) 
			$from_previous = (0xff & ord($from_array[$index - 1]))
				>> (8 - $bits_from_previous);
		else $from_previous = 0;

		$from_this = ord($from_array[$index]) << $bits_from_previous;

		$output .= chr(0x7f & ($from_this | $from_previous));

		/* If we're taking six bits from the previous octet, then
		   there are seven bits in this octet that we need to consider
		   as a character as well. */
		if (6 == $bits_from_previous)
			$output .= chr(0x7f & (ord($from_array[$index]) >> 1));
	return $output;

Like the early Christians, Marx expected the millennium very soon; like
their successors, his have been disappointed--once more, the world has shown
itself recalcitrant to a tidy formula embodying the hopes of some section of
mankind. (Russell)

More information about the Dublin-pm mailing list