Re: cutting a hex string up into a 2d array of binary digits
| From: | Steve Cayford | Date: | Mon, 11 Feb 2002 21:29:22 +0000 |
| Subject: | Re: cutting a hex string up into a 2d array of binary digits | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-16826@lists.php.net to get a copy of this message | ||
I haven't tried it, but the base_convert() function sounds like it could be useful here. Convert hex to a binary string then pop them into the array?
http://www.php.net/manual/en/function.base-convert.php
// this is speculative code written in my email editor and not tested
$hex = ereg_replace("[^0-9a-fA-F]","",$hex); //-kills bogus characters
$rows = array();
for($byte = 0; $byte < 8; $byte++) {
$byteVal = substr($hex,$byte,2);
$byteBin = sprintf("%08s",base_convert($byteVal,16,2));
for($bit = 0; $bit < 8; $bit++) {
$rows[$byte][$bit] = $byteBin[$bit];
}
}
-Steve
On Monday, February 11, 2002, at 02:46 PM, Jon Plummer wrote:
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 -- PHP Database Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php