hex to str php
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.
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:
*/
Hex to str php
Please note: any spaces or colons (:) in the hexadecimal string will be removed.
Need to convert text to hex?
Hexadecimal notation is used as a human-friendly representation of binary values in computer programming and digital electronics. Most programming languages such as Java, ASP.NET, C++, Fortran etc have built-in functions that convert to and from hex format.
What is a Hexadecimal?
Most people are familiar with the decimal, or base-10, system of numbers (all possible numbers can be notated using the 10 digits, 0,1,2,3,4,5,6,7,8,9). With only 10 digits, extra digits need to be used at certain intervals to correctly notate a number. For example, the number 423,004 uses twice as much digits as the number 961.
The hexadecimal, or base-16, system was created to emulate some of the same properties of the common decimal system. The overall difference is, 16 digits are available instead of the 10 digits available to use to notate the value of a number.
The 16 symbols that the hexadecimal system uses are: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E and F. So instead of a decimal symbol of 10, hexadecimal uses an A, and so on and so forth until we get to the decimal of 15 which is notated as F. Similar to the decimal system, after the base of 16 symbols has been used, the appropriate extra digit is added and the order of numbers starts over. In other words, after F, we begin with 10, and so on. To better understand the relationship between the Decimal and Hexadecimal system, check out the table below.
How is Hexadecimal to Text Encoding used in Programming?
Hexadecimal encoding is used by programmers to improve readability of bytes, which are used to communicate to computers. There are a number of benefits for using hexadecimal encoding, including the the higher information density available, as hexadecimal encoding effectively reduces 8 digits of binary code to 2 hexadecimal digits. With this effect, 2 hexadecimal digits expresses any number from 0 to 255, the same scope of numbers as binary’s 8 digits.
Text to Hex Encoding vs. Base 64
While Encoding in Hex is a popular encoding strategy used by progammers, Hex encoding does significantly increase the space used of storage, which reduces the efficiency of your communication with the computer. If storage space is an issue, encoding in Base 64 is recommended as an alternative.
What Is Hex Encoding Used For?
Often, some kind of separator is used to make the encoded data easier for human reading. With 8 bits converted to three characters and each character stored as 1-4 bytes you might use up to 12 bytes (or even more in some cases) for each byte of information.
Again, don’t use hex encoding if storage space is an issue. The encoding is quite easy to read though, so if human readability is an issue, then hex encoding is probably a better choice than base64 encoding.
Using the Free Hex to Text Encoding Tool
The above Hex to Text Converter is very simple to use. Enter or paste the hexadecimal you would like to convert to text, and then click Convert below the paste area. Encoded string will appear in the box below, where you can easily copy it from. For your ease and efficiency, we recommend bookmarking this tool for future use.
String Functions also has created a free online tool to convert string back to hexadecimal. Try it today!
Keywords: hex decode a string text, tool, on line tool, char to hex converter.
Convert hex color to RGB values in PHP
What would be a good way to convert hex color values like #ffffff into the single RGB values 255 255 255 using PHP?
17 Answers 17
If you want to convert hex to rgb you can use sscanf:
I made a function which also returns alpha if alpha is provided as a second parameter the code is below.
The function
Example of function responses
For anyone that is interested this is another very simple way of doing it. This example assumes there is exactly 6 characters and no preceding pound sign.
Here is an example the supports 4 different inputs (abc, aabbcc, #abc, #aabbcc):
You can use the function hexdec(hexStr: String) to get the decimal value of a hexadecimal string.
See below for an example:
This will print rgb(255, 255, 255)
You can try this simple piece of code below.
This will return 123,222,132
My approach to take care of hex colors with or without hash, single values or pair values:
Convert Color Code HEX to RGB
Output
I wrote a simple function like so, which supports an input value with or without beginning # and it can also take 3 or 6 character hex code input:
See also here from CSS Tricks.
I’ve put @John’s answer and @iic’s comment/idea together into a function which can handle both, the usual hex color codes and the shorthand color codes.
A short explanation: