首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP数字操作

问PHP数字操作
EN

Stack Overflow用户
提问于 2010-06-06 23:01:45
回答 3查看 174关注 0票数 0

$ch是一个角色。

我需要把它转换成像这样的2个数字(示例):

代码语言:javascript
复制
$ch = 'A'       =>      ASCII code: 0x41
                =>      Binary: 0100 0001
                =>      {4, 1}

实现这一目标的最简单、最快的方法是什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-06-06 23:06:06

可以使用ord()函数获取ASCII值,然后使用decbin和dechex将其转换为二进制和十六进制格式

http://www.php.net/manual/en/function.ord.php http://www.php.net/manual/en/function.decbin.php http://www.php.net/manual/en/function.dechex.php

票数 4
EN

Stack Overflow用户

发布于 2010-06-06 23:06:01

代码语言:javascript
复制
$i = ord($chr);
$hex = dechex($i);
$ret = array($hex[0], $hex[1]);
票数 1
EN

Stack Overflow用户

发布于 2010-06-06 23:23:28

代码语言:javascript
复制
<?

$ch = 'A';

$hex = base_convert(ord($ch), 10, 16);
$binary = base_convert(ord($ch), 10, 2);
$hex_nibbles = str_split($hex);

$hex_formatted = "0x$hex";

$binary_formatted = str_pad($binary, ceil(strlen($binary)/8)*8, '0', STR_PAD_LEFT);
$binary_formatted = preg_replace('/.{4}/', "$0 ", $binary_formatted);

$hex_nibbles_formatted = '{' . join($hex_nibbles, ', ') . '}';

echo <<<EOF
ASCII code: $hex_formatted
Binary: $binary_formatted
Hex Nibbles: $hex_nibbles_formatted

EOF;

?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2984654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档