I want to print the hexadecimal values of each of the characters in a PHP string. For example, I want to display the hex values of each character in a string where I'm trying to set the fourth character to Control-C (0x03).
我想打印PHP字符串中每个字符的十六进制值。例如,我想在字符串中显示每个字符的十六进制值,我试图将第四个字符设置为Control-C(0x03)。
$str=sprintf('ab1%c',0x03);
for ($cnt=0; $cnt<4; $cnt++)
{
$chr=$str[$cnt];
echo '$str['.$cnt.'] = "'.$str[$cnt].'" = '.sprintf('0x%02x',$chr[0])."\n";
}
var_dump(str_split($str));
What I get is this:
我得到的是这个:
$str[0] = "a" = 0x00
$str[1] = "b" = 0x00
$str[2] = "1" = 0x01
$str[3] = "" = 0x00
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "1"
[3]=>
string(1) ""
}
It seems that $chr
is a string rather than a character and sprintf()
is printing the integer value of a string - zero - instead of the integer value of a single character.
似乎$ chr是一个字符串而不是一个字符,而sprintf()正在打印一个字符串的整数值 - 零 - 而不是单个字符的整数值。
Is it possible to do this in PHP? I was sure there's a way...
是否可以在PHP中执行此操作?我确信有办法......
2 个解决方案
#1
Per @MarkBaker's comment, the solution is to use ord()
to get the character's value:
根据@ MarkBaker的评论,解决方案是使用ord()来获取角色的值:
$str=sprintf('ab1%c',0x03);
for ($cnt=0; $cnt<4; $cnt++)
{
$chr=$str[$cnt];
echo '$str['.$cnt.'] = "'.$str[$cnt].'" = '.sprintf('0x%02x',ord($chr))."\n";
}
var_dump(str_split($str));
yields the expected results:
产生预期结果:
$str[0] = "a" = 0x61
$str[1] = "b" = 0x62
$str[2] = "1" = 0x31
$str[3] = "" = 0x03
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "1"
[3]=>
string(1) ""
}
#2
PHP does not have a char (character) type. You are correct that you are getting a 1-character string as the result.
PHP没有char(字符)类型。你是正确的,你得到一个1个字符的字符串作为结果。
#1
Per @MarkBaker's comment, the solution is to use ord()
to get the character's value:
根据@ MarkBaker的评论,解决方案是使用ord()来获取角色的值:
$str=sprintf('ab1%c',0x03);
for ($cnt=0; $cnt<4; $cnt++)
{
$chr=$str[$cnt];
echo '$str['.$cnt.'] = "'.$str[$cnt].'" = '.sprintf('0x%02x',ord($chr))."\n";
}
var_dump(str_split($str));
yields the expected results:
产生预期结果:
$str[0] = "a" = 0x61
$str[1] = "b" = 0x62
$str[2] = "1" = 0x31
$str[3] = "" = 0x03
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "1"
[3]=>
string(1) ""
}
#2
PHP does not have a char (character) type. You are correct that you are getting a 1-character string as the result.
PHP没有char(字符)类型。你是正确的,你得到一个1个字符的字符串作为结果。