How to treat two chars in a string as a byte?

236 views Asked by At

Consider:

$tag = "4F";

$tag is a string containing two characters, '4' and 'F'. I want to be able to treat these as the upper and lower nibbles respectively of a whole byte (4F) so that I can go on to compute the bit-patterns (01001111)

As these are technically characters, they can be treated in their own right as a byte each - 4 on the ASCII table is 0x52 and F is 0x70.

Pretty much all the PHP built-in functions that allow manipulation of bytes (that I've seen so far) are variations on the latter description: '4' is 0x52, and not the upper nibble of a byte.

I don't know of any quick or built-in way to get PHP to handle this the way I want, but it feels like it should be there.

How do I convert a string "4F" to the byte 4F, or treat each char as a nibble in a nibble-pair. Are there any built in functions to get PHP to handle a string like "4F" or "3F0E" as pairs of nibbles?

Thanks.

1

There are 1 answers

0
bishop On

If you're wanting "the decimal representation of a hex digit", hexdec is one way to go.

If you're wanting "bit pattern for hex digit", then use base_convert. The docs even show an example of this maneuver:

Example #1 base_convert() example

$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);

The above example will output:

101000110111001100110100