2

I found a clever bit of code in the site I'm working on that uses hex values to store an array of toggleable variables.

(For example, D in hex being 1101 in binary, means the first toggle is one, the second is off, and the third and fourth are on).

I looked at unpack, but either I didn't understand it or it's not the right function for me. I also considered splitting the whole thing character by character and then sending each character through a switch that then drops values into an array, but that seems way too cumbersome and inelegant.

So, how do I turn a string of hex-based characters into an ordered array of Boolean values?

3
  • 1
    So you want to convert a string like: "D" into an array, like: Array ( True, True, False, True ) ? Commented Sep 21, 2015 at 23:16
  • 1
    What about, for example, hex digit 1? Should the resulting array be [True] or [False, False, False, True] or something else? Commented Sep 21, 2015 at 23:34
  • @lafor 1 should be False, False, False, True. Commented Sep 22, 2015 at 15:26

1 Answer 1

2

How about:

function hex_to_bool_array($hex_string, $pad_length = 0) {
   return array_map(
      function($v) { return (bool) $v; },
      str_split(str_pad(base_convert($hex_string, 16, 2), $pad_length, '0', STR_PAD_LEFT))
   );
}

var_dump(hex_to_bool_array('D'));

// array (size=4)
//   0 => boolean true
//   1 => boolean true
//   2 => boolean false
//   3 => boolean true;

var_dump(hex_to_bool_array('7', 8));

// array (size=8)
// 0 => boolean false
// 1 => boolean false
// 2 => boolean false
// 3 => boolean false
// 4 => boolean false
// 5 => boolean true
// 6 => boolean true
// 7 => boolean true
Sign up to request clarification or add additional context in comments.

2 Comments

decbin(hexdec($hex_string)) Why not just: base_convert($hex_string, 16, 2) ?
@Rizier123 Good point, I forgot there's base_convert(). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.