百科狗-知识改变命运!
--

dechex() - 十进制转换为十六进制 - php 数学函数

百变鹏仔1年前 (2023-11-21)阅读数 13#技术干货
文章标签转换为

dechex()

(PHP 4, PHP 5, PHP 7)

十进制转换为十六进制

说明

dechex(int $number): string

返回一字符串,包含有给定$number参数的十六进制表示。

所能转换的最大数值为十进制的PHP_INT_MAX* 2 + 1(或-1):在 32 位平台上是十进制的4294967295,其dechex()的结果为ffffffff

参数

$number

要转换的十进制值

dechex() - 十进制转换为十六进制 - php 数学函数

PHP 的integer类型是有符号的,但dechex()处理无符号整数,负正数会以无符号处理。

返回值

$number的16进制表示

范例

Example #1dechex()例子

以上例程会输出:

a
2f

大整数的dechex()例子

以上例程会输出:

ffffffff
ffffffff
ffffffff

参见

  • hexdec() 十六进制转换为十进制
  • decbin() 十进制转换为二进制
  • decoct() 十进制转换为八进制
  • base_convert() 在任意进制之间转换数字
Be very careful calling dechex on a number if it's stored in a string.
For instance:
The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.
dechex(4294967295) => FFFFFFFF //CORRECT
BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.
dechex('4294967295') => 7FFFFFFF //WRONG!
so you'll need to cast to a float:
dechex((float) '4294967295') => FFFFFFFF //CORRECT
This took me FOREVER to figure out, so hopefully I just saved someone some time.
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
  $hexvalues = array('0','1','2','3','4','5','6','7',
        '8','9','A','B','C','D','E','F');
  $hexval = '';
   while($number != '0')
   {
    $hexval = $hexvalues[bcmod($number,'16')].$hexval;
    $number = bcdiv($number,'16',0);
  }
  return $hexval;
}
// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
  $decvalues = array('0' => '0', '1' => '1', '2' => '2',
        '3' => '3', '4' => '4', '5' => '5',
        '6' => '6', '7' => '7', '8' => '8',
        '9' => '9', 'A' => '10', 'B' => '11',
        'C' => '12', 'D' => '13', 'E' => '14',
        'F' => '15');
  $decval = '0';
  $number = strrev($number);
  for($i = 0; $i 
A less elegant but (perhaps) faster way to pad is with substr with a negative length argument. I use it in this tiny function which formats computed rgb color codes for style sheets: 
Here is a very small zeropadding that you can use for numbers:
function zeropad($num, $lim)
{
  return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}
zeropad("234",6);
will produce:
000234
zeropad("234",1);
will produce:
234
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.
In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.
Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome! 
If you need to generate random HEX-color, use this:

Enjoy.
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it's behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).
function &formatIntegerForOutput($value) {
  $text = "00000000";
  $transString = "0123456789ABCDEF";
  // handle highest nibble (nibble 7):
    $nibble = $value & 0x70000000;
    $nibble >>= 28;
    if ($value  0; $a --) {
      $nibble = $value & 0x0000000F;
      $text[$a] = $transString[$nibble];
      $value >>= 4;
    }
  return $text
}
this function should be not too slow and is really simple.
I don't know, if the DECHEX function in the future will pad it's output to ever be 8 characters in length - so for backward compatibility reasons even in future PHP versions i avoided to use it.
Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.
function hexColor($color) {
 return dechex(($color[0]
I was confused by dechex's size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs. 
Easiest :P way to create random hex color: 
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0' just before processing them.
for example 

will print '7FFFFFFF'
but it should print 'A269BBA6'
When adding '+0' php will handle the 32bit unsigned integer
correctly

will print 'A269BBA6'
Create Random Hex Color:
function make_seed() { 
  list($usec, $sec) = explode(' ', microtime()); 
  return (float) $sec + ((double) $usec * 100000); 
} 
function rand_hex() {
  mt_srand(make_seed()); 
  $randval = mt_rand(0,255);
  //convert to hex
  return sprintf("%02X",$randval);
}
function random_color(){
  return "#".rand_hex().rand_hex().rand_hex();
}
hme ;)
If you need to convert RGB-color into HEX-color, use this: 
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:
base_convert('2190964402', 10, 16); // 829776b2
I wrote this to convert hex into signed int, hope this helps someone out there... peace :) 
warning jbleau dec_to_hex method is buggy, avoid it.
dec_to_hex('9900000397')-->24e16048f
dec_to_hex('9900000398')-->24e16048f
dec_to_hex('9900000399')-->24e16048f
Javascript Crypt: 
I like the example with the bitwise operations but if the value of color[0] is less than 16 it's not accurate:
example:
color[0]: 0;
color[1]: 0;
color[2]: 255;
 function hexColor($color) {
 return dechex(($color[0]
I figured out another way to do this:
if you have a very long decimal number in gmp format (you can always create a gmp number with gmp_init($numberstring), you can simply do gmp_strval($gmpnumber, 16), where $gmpnumber is your gmp number, and the 16 is the base you want to transform it to. Worked for me like a charm, also works for other bases.
If you want to create or parse signed Hex values:

Also note that ('0x' . $str + 0) is faster than hexdec()
Or you could use this for an RGBA color.
  function toAlphaColor($n,$a)
  {
    $rgb = substr("000000".dechex($n),-6);
    $alpha = substr("00".dechex($a),-2);
    return("#".$rgb.$alpha);
  }
for mac address 
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example. 
Warning for use on 64 bit machines! The Extra length matters!
32bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff
64bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff
so far it is ok. But for slightly bigger numbers:
32bit machine:
php -r 'echo dechex(4294967296);'
output: 0
64bit machine:
php -r 'echo dechex(4294967296);'
output: 100000000
note the difference!
This is particularly important when converting negative numbers:
64bit machine:
php -r 'echo dechex(-1);'
output: ffffffffffffffff
32bit machine:
php -r 'echo dechex(-1);'
output: ffffffff
If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
I see a lot of less-than-optimal functions posted on this page, so I feel I have to give some better examples... 
due to the sheer size of this collection, I have made it available on my server, rather than copy/paste it into these comments.
http://ryo-ohki.4th-age.com/demos/able.php
and
http://ryo-ohki.4th-age.com/demos/able.phps
dechex replacement function from above source: 
This function will take a string and convert it into a hexdump.
e.g.
3c666f6e 74207369 7a653d22 33223e4c L
6561726e 20686f77 20746f20 62652061 earn.how.to.be.a
function hexdump($string) {
  $hex="";
  $substr = "";
  for ($i=0; $i 
Here's my version of a red->yellow->green gradient:

and use it like this:

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)