php bin to hex
bin2hex
(PHP 4, PHP 5, PHP 7, PHP 8)
bin2hex — Преобразует бинарные данные в шестнадцатеричное представление
Описание
Список параметров
Возвращаемые значения
Возвращает шестнадцатеричное представление указанной строки.
Смотрите также
User Contributed Notes 23 notes
This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this:
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:
Ok, this is a better version than my previous poor example.
Running this in shell creates a progress indicator. Very useful if used when parsing large log files for instance.
the browser will show foo@bar.
Convenient way of generating API keys
= bin2hex ( random_bytes ( 32 )); // generates 64 characters long string /^[0-9a-f]<64>$/
?>
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:
hex2bin can be useful to insert data into BLOB binary fields.
for example if you want to insert the content of a file :
// use the usual mysql_connect() function
Because the way back (hex2bin) doesn’t exist on php, i’ve written another little function without using commands like pack:
// Convert a hex-string to binary-string (the way back from bin2hex)
echo bin2hex ( ‘Hello’ ); // result: 48656c6c6f
echo hex2bin ( ‘48656c6c6f’ ); // result: Hello
?>
Regarding the fabled hex2bin, the easiest way I’ve found to «replace» it is the following call to function pack():
In an attempt to dodge spam bots I’ve seen people (including myself) hex encode their email addresses in «mailto» tags. This is the small chunk of code I wrote to automate the process:
would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d
I thought it’ll give me an «F» if i give it a «1111».
Here’s something to convert a binary-string into a hex-string and other direction too:
Here’s a function to check if a string contains any 7-bit GSM characters.
It might come useful for people working on SMS platforms.
Here’s a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again. For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters. For example, if you want to store code snibbets in a mySQL text field:
printf(«here’s some \»text\».»);
If you INSERT this into mySQL, it probably won’t come out in friendly executable format, and you can’t escape all double-quotes, nor can you strip out all the slashes. One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way:
function to search a character in a normal string change this for a hexadecimal and take the especifical char code in hexa and replace this char and return the string
Some gave a function to convert a hex code back into a simple text (human readable ASCII :P)
Some else gave a function that makes use of bin2hex to convert URLs into something like %12%34%56
Here is a function to go from the form %12%34%56 back into ASCII
Note that this function can easily be changed in order to transform any hex code into ASCII
‘hope this helps 🙂
Regards
-Tsuna
This function undoes it (converts back into ASCII).
Hopefully this helps someone.
It just displays an html representation of hex data, much like a hex viewer would.
Postgresql return result in bytea so don’t forget to convert_from
I needed a little function that will print the binary as a string, here it comes.
Работа с бинарными данными в 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 — конвертирование 2 двоичных и десятичных данных
octdec, decoct — конвертирование 9 десятичных и восьмеричных данных
hexdec, dechex — конвертирование 16 десятичных и шестнадцатиричных данных
ord, chr — конвертирование 256 десятичных и символьных (ascii) данных
base64_encode, base64_decode — конвертирование 256 данных, но в отличие от предыдущих форматов, данные одного значения не кодируются в 6 битах что-бы получить 64 значения, а по прежнему в 8 битах — остальные символы просто не используются.. Из-за этого формат менее эффективен в хранении, но для человека в виде текста более компактен чем нули, единицы или hex.
Отличительная и неприятная особенность, конечно в том что каждая из функций конвертирует данные со строго определённым размером данных. Обычно же у нас есть какой-то пакет данных. Их можно проконвертировать в цикле с определённым шагом..
Читайте также
Backdoor — тайный ход, лазейка. Разумное человечество использовало всегда запасной случай что-бы не попасть впросак. К примеру те же замки,…
Сортировку можно производить на стороне сервера в БД (самое логичное решение), но зачастую система не продумана заранее настолько и получается…
Стандартные библиотеки PHP умеют генерировать только целые случайные числа. Однако, возникают задачи где нужно не целое рандомное число с максимально…
bin2hex
bin2hex — Преобразует бинарные данные в шестнадцатеричное представление
Описание
Список параметров
Возвращаемые значения
Возвращает шестнадцатеричное представление указанной строки.
Смотрите также
Коментарии
In an attempt to dodge spam bots I’ve seen people (including myself) hex encode their email addresses in «mailto» tags. This is the small chunk of code I wrote to automate the process:
would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:
Hopefully this helps someone.
It just displays an html representation of hex data, much like a hex viewer would.
This function undoes it (converts back into ASCII).
Some gave a function to convert a hex code back into a simple text (human readable ASCII :P)
Some else gave a function that makes use of bin2hex to convert URLs into something like %12%34%56
Here is a function to go from the form %12%34%56 back into ASCII
Note that this function can easily be changed in order to transform any hex code into ASCII
function to search a character in a normal string change this for a hexadecimal and take the especifical char code in hexa and replace this char and return the string
I thought it’ll give me an «F» if i give it a «1111».
Here’s something to convert a binary-string into a hex-string and other direction too:
Ok, this is a better version than my previous poor example.
Running this in shell creates a progress indicator. Very useful if used when parsing large log files for instance.
I needed a little function that will print the binary as a string, here it comes.
Here’s a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again. For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters. For example, if you want to store code snibbets in a mySQL text field:
printf(«here’s some \»text\».»);
If you INSERT this into mySQL, it probably won’t come out in friendly executable format, and you can’t escape all double-quotes, nor can you strip out all the slashes. One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way:
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:
the browser will show foo@bar.
This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this:
hex2bin can be useful to insert data into BLOB binary fields.
for example if you want to insert the content of a file :
// use the usual mysql_connect() function
Because the way back (hex2bin) doesn’t exist on php, i’ve written another little function without using commands like pack:
// Convert a hex-string to binary-string (the way back from bin2hex)
echo bin2hex ( ‘Hello’ ); // result: 48656c6c6f
echo hex2bin ( ‘48656c6c6f’ ); // result: Hello
?>
Regarding the fabled hex2bin, the easiest way I’ve found to «replace» it is the following call to function pack():
Here’s a function to check if a string contains any 7-bit GSM characters.
It might come useful for people working on SMS platforms.
Postgresql return result in bytea so don’t forget to convert_from
Convenient way of generating API keys
= bin2hex ( random_bytes ( 32 )); // generates 64 characters long string /^[0-9a-f]<64>$/
?>
bin2hex
bin2hex — Преобразует бинарные данные в шестнадцатиричное представление
Описание
Список параметров
Возвращаемые значения
Возвращает шестнадцатиричное представление указанной строки.
Смотрите также
Коментарии
In an attempt to dodge spam bots I’ve seen people (including myself) hex encode their email addresses in «mailto» tags. This is the small chunk of code I wrote to automate the process:
would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:
Hopefully this helps someone.
It just displays an html representation of hex data, much like a hex viewer would.
This function undoes it (converts back into ASCII).
Some gave a function to convert a hex code back into a simple text (human readable ASCII :P)
Some else gave a function that makes use of bin2hex to convert URLs into something like %12%34%56
Here is a function to go from the form %12%34%56 back into ASCII
Note that this function can easily be changed in order to transform any hex code into ASCII
function to search a character in a normal string change this for a hexadecimal and take the especifical char code in hexa and replace this char and return the string
I thought it’ll give me an «F» if i give it a «1111».
Here’s something to convert a binary-string into a hex-string and other direction too:
Ok, this is a better version than my previous poor example.
Running this in shell creates a progress indicator. Very useful if used when parsing large log files for instance.
I needed a little function that will print the binary as a string, here it comes.
Here’s a modified version of an earlier post (asc2bin and bin2asc) to convert an incoming ascii string to hex and out again. For example, this is really useful if you want to insert data into a mySQL database which contains both escaped and non-escaped characters. For example, if you want to store code snibbets in a mySQL text field:
printf(«here’s some \»text\».»);
If you INSERT this into mySQL, it probably won’t come out in friendly executable format, and you can’t escape all double-quotes, nor can you strip out all the slashes. One solution is to just convert the string to hex, store it in hex, then convert back to ascii before using it in some way:
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:
the browser will show foo@bar.
This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this:
hex2bin can be useful to insert data into BLOB binary fields.
for example if you want to insert the content of a file :
// use the usual mysql_connect() function
Because the way back (hex2bin) doesn’t exist on php, i’ve written another little function without using commands like pack:
// Convert a hex-string to binary-string (the way back from bin2hex)
echo bin2hex ( ‘Hello’ ); // result: 48656c6c6f
echo hex2bin ( ‘48656c6c6f’ ); // result: Hello
?>
Regarding the fabled hex2bin, the easiest way I’ve found to «replace» it is the following call to function pack():
Here’s a function to check if a string contains any 7-bit GSM characters.
It might come useful for people working on SMS platforms.
Postgresql return result in bytea so don’t forget to convert_from
Convenient way of generating API keys
= bin2hex ( random_bytes ( 32 )); // generates 64 characters long string /^[0-9a-f]<64>$/
?>
hexdec
(PHP 4, PHP 5, PHP 7, PHP 8)
hexdec — Переводит число из шестнадцатеричной системы счисления в десятичную
Описание
hexdec() игнорирует любые обнаруженные не шестнадцатеричные символы. Начиная с PHP 7.4.0, предоставление любых некорректных символов устарело.
Список параметров
Шестнадцатеричная строка для преобразования
Возвращаемые значения
Десятичное представление hex_string
Список изменений
Версия | Описание |
---|---|
7.4.0 | Передача некорректных символов будет выдавать уведомление об устаревании. Результат будет вычислен так, как если бы некорректные символы не существовали. |
Примеры
Пример #1 Пример использования hexdec()
( hexdec ( «See» ));
var_dump ( hexdec ( «ee» ));
// в обоих случаях будет выведено «int(238)»
var_dump ( hexdec ( «that» )); // выведет «int(10)»
var_dump ( hexdec ( «a0» )); // выведет «int(160)»
?>
Примечания
Смотрите также
User Contributed Notes 31 notes
Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.
Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.
For eg: #FFF and #FFFFFF will produce the same result
If you want to create or parse signed Hex strings:
Here is other function to transform a MAC Address to decimal:
Here’s my hexdec function for greater numbers using BC Math
After esnhexdec from «rledger at gmail dot com», the esndechex:
The issue I’ve seen with the existing hex to dec conversion routines is the lack of error-trapping. I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one. I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps. As such I’ve seen multiple formats for writing hex colors.
For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff
Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.
/*
To use simply use the following function call:
$color = convert_color(«#FF»);
this will return the following assoc array if successful:
*[success] = true
*[r] = 255
*[g] = 0
*[b] = 0
or copy and paste the following code:
$hex = «FFFFFF»; // Color White
$color = convert_color($hex);
var_dump($color);
*/
?>
As you can see, the function «convert_color» accepts a hex # in most acceptable formats and returns an associative array. [success] is set to TRUE if the function succeeds and FALSE if not. The array members [r], [g] and [b] hold the red,green and blue values respectively. If it fails, [error] holds a custom error message.
«strip_chars» is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function. It will accept either a single value or an array of values for the characters to remove.