cutting a hex string up into a 2d array of binary digits

From: Date: Mon, 11 Feb 2002 20:46:26 +0000
Subject: cutting a hex string up into a 2d array of binary digits
Groups: php.db 
Request: Send a blank email to php-db+get-16824@lists.php.net to get a copy of this message
I've got a (user supplied) string of sixteen characters that represents 8 bytes in hex (such as "006cbebe5c381000") that correspond to an 8x8 grid of pixels, one bit each (such as 00000000 [00] 01101100 [6c] 10111110 [be] 10111110 [be] 01011100 [5c] 00111000 [38] 00010000 [10] 00000000 [00]) and I'm trying to cup up and parse that string into a two-dimensional array that contains 1|0 or true|false values for each of the corresponding bits. I've been fiddling around with pack(), unpack() and substr(), and have something that works: $hex = ereg_replace("[^0-9a-fA-F]","",$hex); //-kills bogus characters $hex = pack("H" . strlen($hex), $hex); $rows = unpack("C*", $hex); //-makes an array of single-byte decimal values $y = 0; foreach ($rows as $cols) { $cols = str_pad(decbin($cols), 8, "0", STR_PAD_LEFT); //-makes sure each string is eight characters for ($x = 0; $x < strlen($cols); $x++) { $pix[$y][$x] = substr($cols, $x, 1); } $y++; } But it is kinda slow. I've been trying to simplify, make better use of foreach(), etc., but I'm obviously not understanding unpack() very well and needing help with finding the lightest, least brute-force approach. Any ideas? -- Jon Plummer jon@jonplummer.com

« previous php.db (#16824) next »