E235
E235

Reputation: 13500

Why PHP pack("h*", 0x41) function prints wrong ASCII text

I read here how to use the pack function in PHP.

According to the documentation the h format will print

Hex string, low nibble first

I wanted to check how it works so I ran the following command:

echo pack("h*", 0x41) . "<br />"  ;

You can try it on this online PHP commands website.

It prints the character V.
But 0x41 is 65 in decimal, 01000001 in binary and A in ASCII/ANSI.
Why it printed V and not A ?
I understand that it packs it in binary structure, but binary structure is 01000001 which should be A.

Upvotes: 1

Views: 207

Answers (2)

Jonni
Jonni

Reputation: 36

I think you use the wrong format,The format of pack introduce like this:

  1. h : Hex string, low nibble first
  2. c : signed char

So you try it like this:

echo pack("h*", 0x41) . "<br />"  ;

It prints the character V.

When you try it like this:

echo pack("c*", 0x41) . "<br />"  ;

It prints the character A.

Upvotes: 1

ALFA
ALFA

Reputation: 1744

Exactly, using the right format for h, low nibble first, so:

echo pack("h*", "14");

Output:

A

Same output for H with high nibble first:

echo pack("H*", "41");

It's better to use H for more intuitiveness.

Upvotes: 1

Related Questions