php 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.
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.
Как перевести hex в стринг?
Подскажите как можно перевести hex данные в строку?
Требуется вывести Хеш в строку функцией echo, не могу найти нужную функцию,
Хеш находится в виде готового файла, вычитываю его с помощью file_get_content ()
Нашёл вот такую:
но она «съедает» Нули, например из данных FF05B735 выведет строку FF5B735
Не совсем понятно, что Вы хотите сделать.
Перевести число из шестнадцатеричного в десятичное?
hexdec
Напишите пример, что на входе и что должно быть на выходе.
Хочу вывести в строку из содержимого бинарного файла.
Вот содержимое файла (открыл в WinHex)
Надо получить такую строку FF05B735DE18507705C7256F0198CFF1
У меня сейчас получается вот так:
string(29) «FF5B735DE1850775C7256F198CFF1»
А надо вот так:
string(32) «FF05B735DE18507705C7256F0198CFF1«
Спасибо, все работает.
P.S. Ночью пробовал эту функцию в Online PHP Compiler, выдавало совершенно не то,
Теперь понял почему, я изначально вставлял СТРОКУ, а не содержимое файла.
У меня получалось так:
Что совершенно не Верно.
Как перевести hex в стринг?
Подскажите как можно перевести hex данные в строку?
Требуется вывести Хеш в строку функцией echo, не могу найти нужную функцию,
Хеш находится в виде готового файла, вычитываю его с помощью file_get_content ()
Нашёл вот такую:
но она «съедает» Нули, например из данных FF05B735 выведет строку FF5B735
Не совсем понятно, что Вы хотите сделать.
Перевести число из шестнадцатеричного в десятичное?
hexdec
Напишите пример, что на входе и что должно быть на выходе.
Хочу вывести в строку из содержимого бинарного файла.
Вот содержимое файла (открыл в WinHex)
Надо получить такую строку FF05B735DE18507705C7256F0198CFF1
У меня сейчас получается вот так:
string(29) «FF5B735DE1850775C7256F198CFF1»
А надо вот так:
string(32) «FF05B735DE18507705C7256F0198CFF1«
Спасибо, все работает.
P.S. Ночью пробовал эту функцию в Online PHP Compiler, выдавало совершенно не то,
Теперь понял почему, я изначально вставлял СТРОКУ, а не содержимое файла.
У меня получалось так:
Что совершенно не Верно.
dechex
(PHP 4, PHP 5, PHP 7, PHP 8)
dechex — Переводит число из десятичной системы счисления в шестнадцатеричную
Описание
Список параметров
Десятичное значение для преобразования
Так как тип PHP int является знаковым, а dechex() работает с беззнаковыми целыми, то отрицательные целые воспринимаются как беззнаковые.
Возвращаемые значения
Примеры
Пример #1 Пример использования dechex()
Результат выполнения данного примера:
Пример #2 Пример использования dechex() с большими целыми
Результат выполнения данного примера:
Смотрите также
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:
*/