Convert Integer to hex values in PHP

2019-07-19 02:55发布

How can I convert the numbers in the first class in PHP into the numbers in the second class, is there a built in function to convert the numbers? Also is my title " Convert Integer to hex values" even correct?

class Permission {
    const READ         = 1;
    const UPDATE       = 2;
    const DELETE       = 4;
    const COMMENT      = 8;
    const GRANT        = 16;
    const UNDELETE     = 32;
    const WHATEVER     = 64;
}

into this

class Permission {
    const READ     = 0x0001;
    const UPDATE   = 0x0002;
    const DELETE   = 0x0004;
    const COMMENT  = 0x0008;
    const GRANT    = 0x0010;
    const UNDELETE = 0x0020;
    const WHATEVER = 0x0040;
}

UPDATE

To elaborate a little more of what I am trying to do.
I currently use the first class with a bitmask class for settings,
somebody suggested to me to change to the format in the second class though.
However I did not know how they came up with the 0x0020 style numbers from the numbers in my 1st class.

I now see how to get the 20 from 32 but I do not know how or why they had added 0x00 in front of it to make 0x0020 to replace my original 32

标签: php
3条回答
放我归山
2楼-- · 2019-07-19 03:42

You want:

dechex()

http://php.net/manual/en/function.dechex.php

Which is decimal to hex.

查看更多
\"骚年 ilove
3楼-- · 2019-07-19 03:48

I'm a little confused here... 0x01 = 1. 0x020 = 32, etc.

Are you looking for some of the string formatters like available in printf/sprintf? You can use the %x marker to output hex values.

edit: Also, yes, your conversions are correct.

查看更多
霸刀☆藐视天下
4楼-- · 2019-07-19 03:55

You can't just type in the hex numbers to begin with?

Try sprintf()/printf() to conver them on the fly:

printf('%x', 42); // 2a
查看更多
登录 后发表回答