php int to hex
dechex
(PHP 4, PHP 5, PHP 7, PHP 8)
dechex — Decimal to hexadecimal
Description
Returns a string containing a hexadecimal representation of the given unsigned num argument.
Parameters
The decimal value to convert.
As PHP’s int type is signed, but dechex() deals with unsigned integers, negative integers will be treated as though they were unsigned.
Return Values
Examples
Example #1 dechex() example
The above example will output:
Example #2 dechex() example with large integers
The above example will output:
See Also
User Contributed Notes 33 notes
Be very careful calling dechex on a number if it’s stored in a string.
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.
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).
Here is a very small zeropadding that you can use for numbers:
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 😛 way to create random hex color:
Create Random Hex Color:
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();
>
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]
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
warning jbleau dec_to_hex method is buggy, avoid it.
I wrote this to convert hex into signed int, hope this helps someone out there. peace 🙂
If you want to create or parse signed Hex values:
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!
To force the correct usage of 32-bit unsigned integer in some functions, just add ‘+0’ just before processing them.
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.
echo decrom ( romdec ( «XXXX» ));
?>
Warning for use on 64 bit machines! The Extra length matters!
so far it is ok. But for slightly bigger numbers:
note the difference!
This is particularly important when converting negative numbers:
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).
This function will take a string and convert it into a hexdump.
3c666f6e 74207369 7a653d22 33223e4c L
6561726e 20686f77 20746f20 62652061 earn.how.to.be.a
Here’s my version of a red->yellow->green gradient:
Here’s a function which works for decimal values up to 9007199254740992 (hex 20000000000000).
Heres a example of dec to html hex gradient. Have fun 🙂
//Amount of gradients
$l = 20;
//Start color
$start[0] = «255»; //red
$start[1] = «0»; //green
$start[2] = «255»; //blue
//End color
$end[0] = «255»; //red
$end[1] = «255»; //green
$end[2] = «255»; //blue
$rgb[$i] = dechex($rgb[$i]);
$rgb[$i] = strtoupper($rgb[$i]);
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/
Convert integer to hexadecimal and back again
How can I convert the following?
2934 (integer) to B76 (hex)
Let me explain what I am trying to do. I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value. The main reason is because it’s shorter.
So not only do I need to go from integer to hex but I also need to go from hex to integer.
Is there an easy way to do this in C#?
10 Answers 10
Try the following to convert it to hex
I really question the value of this, though. You’re stated goal is to make the value shorter, which it will, but that isn’t a goal in itself. You really mean either make it easier to remember or easier to type.
If you mean easier to remember, then you’re taking a step backwards. We know it’s still the same size, just encoded differently. But your users won’t know that the letters are restricted to ‘A-F’, and so the ID will occupy the same conceptual space for them as if the letter ‘A-Z’ were allowed. So instead of being like memorizing a telephone number, it’s more like memorizing a GUID (of equivalent length).
If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It’s likely to be more difficult to type, because it won’t be a word their fingers recognize.
A much better option is to actually let them pick a real username.
Работа с бинарными данными в php
PHP как язык плохо подходит для работы бинарными данными напрямую. Но иногда приложения должны взаимодействовать по таким протоколам, где размер пакетов очень важен или родным форматом данных для какого-то приложения, который никем в красивый json или xml не переводится.
Целые типы данных
Напоминаю какие типы данных есть в Си, на котором основан php
Тип | Размер памяти | Значений всего |
char | 1 байт = 8 бит | 256 |
int | 2 байт = 16 бит | 2^16=65536 |
short | 2 байта | |
long | 4 байта = 32 бита | 4294967295 |
Char при этом используется универсально согласно ASCII табличке как в качестве явного кодирования текста, так и вспомогательными маркерами. Про float я умолчу, ибо мне не понадобилось.
Нотация
Если с бинарными данными не работать, то можно и забыть основы языка. С целыми числами на основании 10 всё понятно, но обычно значения длинных данных в них не пишут. Это объясняет табличку выше.
Кроме этого, если вы переписываетесь с коллегами которые пишут на си, то они могут обозначать приставками или окончаниями
Порядок битов
Честно, для меня было откровением что порядок в данных имеет значение. Я привык что 123 уже подразумевает где сотни, десятки и единицы, но для компьютера ведь всё равно. Конечно одно дело порядок написания для человека.. но тут другое — порядок записи байтов в зависимости от адреса. И больше всего удивительно что архитектуры на уровне работы с памятью разделились — x86 на стороне little endian, а за big endian SPARC и прочие. Поэтому если вы интегрируете разные архитектуры с бинарным форматом данных — договоритесь которая система будет работать.
Операции
1. Бинарное чтение файла — fopen(«binaryfile»,»b»);
2. Битовые маски — популярный метод хранить много булевых значений в одной переменной и включать/проверять с помощью AND/OR операций. Если вы когда либо выполняли chmod 755, то уже включали эти флажки на привилий.
3. Побитовые сдвиги — помогают работать с битовыми масками и с битами в вообще
4. Cyclic redundancy check
Вот пример самого короткого кода для CRC16 CCITT
5. Упаковка
Если вы обычную переменную в php начнёте сохранять в файл, то она наверняка не будет оптимальной. А если таких однородных данных много — то тем более имеет смысл создать более компактную версию.
Например, если вы хотите число 250 записать в один байт как char-тип, вместо того что-бы писать «строкой» в три символа, как то будет делать php по умолчанию, пишем:
Первый аргумент это формат данных по длине. Если все данные char-типа, то можно написать c* как в регулярных выражениях, получить повторение типа. Можно написать c4, что будет аналогично cccc (четыре повторения данных char-типа)
Всего типов данных много..
Сам не проверял, но говорят что unsigned int получить не так то просто
6. Распаковка
Заметьте что pack я тут использую вместо hex2bin, которая недоступна для версий php менее 5.4
7. Конвертирование
base_convert — конвертирование строковых представлений чисел из любого основания в другое (скажем 16 в 2)
bindec, decbin — конвертирование 7 двоичных и десятичных данных
octdec, decoct — конвертирование 9 десятичных и восьмеричных данных
hexdec, dechex — конвертирование 16 десятичных и шестнадцатиричных данных
ord, chr — конвертирование 256 десятичных и символьных (ascii) данных
base64_encode, base64_decode — конвертирование 256 данных, но в отличие от предыдущих форматов, данные одного значения не кодируются в 6 битах что-бы получить 64 значения, а по прежнему в 8 битах — остальные символы просто не используются.. Из-за этого формат менее эффективен в хранении, но для человека в виде текста более компактен чем нули, единицы или hex.
Отличительная и неприятная особенность, конечно в том что каждая из функций конвертирует данные со строго определённым размером данных. Обычно же у нас есть какой-то пакет данных. Их можно проконвертировать в цикле с определённым шагом..
Читайте также
Backdoor — тайный ход, лазейка. Разумное человечество использовало всегда запасной случай что-бы не попасть впросак. К примеру те же замки,…
Сортировку можно производить на стороне сервера в БД (самое логичное решение), но зачастую система не продумана заранее настолько и получается…
Стандартные библиотеки PHP умеют генерировать только целые случайные числа. Однако, возникают задачи где нужно не целое рандомное число с максимально…
dechex
dechex — Переводит число из десятичной системы счисления в шестнадцатеричную
Описание
Список параметров
Десятичное значение для преобразования
Так как тип PHP integer является знаковым, а dechex() работает с безнаковыми целыми, то отрицательные целые воспринимаются как безнаковые.
Возвращаемые значения
Примеры
Пример #1 Пример использования dechex()
Результат выполнения данного примера:
Пример #2 Пример использования dechex() с большими целыми
Результат выполнения данного примера:
Смотрите также
Коментарии
Heres a example of dec to html hex gradient. Have fun 🙂
//Amount of gradients
$l = 20;
//Start color
$start[0] = «255»; //red
$start[1] = «0»; //green
$start[2] = «255»; //blue
//End color
$end[0] = «255»; //red
$end[1] = «255»; //green
$end[2] = «255»; //blue
$rgb[$i] = dechex($rgb[$i]);
$rgb[$i] = strtoupper($rgb[$i]);
Here’s a function which works for decimal values up to 9007199254740992 (hex 20000000000000).
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.
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]
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).
Create Random Hex Color:
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();
>
Easiest 😛 way to create random hex color:
Here’s my version of a red->yellow->green gradient:
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/
This function will take a string and convert it into a hexdump.
3c666f6e 74207369 7a653d22 33223e4c L
6561726e 20686f77 20746f20 62652061 earn.how.to.be.a
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
Here is a very small zeropadding that you can use for numbers:
will produce:
000234
Warning for use on 64 bit machines! The Extra length matters!
so far it is ok. But for slightly bigger numbers:
note the difference!
This is particularly important when converting negative numbers:
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).
A handy little function to convert HEX colour codes to «web safe» colours.
?>
Example: color_mkwebsafe(‘0e5c94’);
Produces: 006699
Hope this helps someone out. Happy coding. 🙂
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.
echo decrom ( romdec ( «XXXX» ));
?>
Be very careful calling dechex on a number if it’s stored in a string.
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.
To force the correct usage of 32-bit unsigned integer in some functions, just add ‘+0’ just before processing them.
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!
I was confused by dechex’s size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.
How to convert int array to hex string
I want to convert an int array to a hex string. I am unsure if I am doing this correctly.
2 Answers 2
Assuming I understand your intention, there are two problems with the code:
here’s a quick and dirty working code example
You say you get results every second from your remote object. On a slow machine with large arrays it is possible that it could take a significant number of milliseconds to convert a long int[] to a hex string using your method using your (or rather Malt’s corrected version of your) method.
A much faster method would be to get each 4-bit nibble from each int using bit shifting, and get the appropriate hex character from a static hex lookup array (note this does base-16 encoding, you would get shorter strings from something like base-64 encoding):
Testing this vs your original method using caliper (microbenchmark results here) shows this is around 11x faster † (caveat: on my machine). EDIT For anyone interested in running this and comparing the results, there is a gist here with the source code.
Even for a single element array
This is around 2x to 4x faster depending on array length (on my machine™). The mean runtime results (in ns) are:
† Disclaimer: Micro-benchmarking is dangerous to rely on as an indication of performance in a real world app, but caliper is a good benchmarking framework, jmh is imho better. A performance difference of 10x 4x, with very small standard deviation, in caliper a good t-test result is enough to indicate a good performance increase even inside a more complex application.