Php implements binary conversion (binary, octal, and hexadecimal) to implement code conversion. For more information, see. Convert decimal to binary, octal, and hexadecimal
To convert from decimal to other hexadecimal values, the number is used to continuously divide by the number of hexadecimal values to be converted and read the remainder. Connect them together.
The code is as follows:
/**
* Convert decimal to binary, octal, or hexadecimal with zero padding before the digits being insufficient *
*
* @ Param array $ datalist input data array (100,123,130)
* @ Param int $ bin conversion can be: 2, 8, 16
* @ Return array returns the data array () and returns the format in which no data is converted.
* @ Copyright chengmo QQ: 8292669
*/
Function decto_bin ($ datalist, $ bin)
{
Static $ arr = array (, 'A', 'B', 'C', 'D', 'e ', 'F ');
If (! Is_array ($ datalist) $ datalist = array ($ datalist );
If ($ bin = 10) return $ datalist; // ignore in the same hexadecimal format
$ Bytelen = ceil (16/$ bin); // Obtain the length of a byte in $ bin notation.
$ AOutChar = array ();
Foreach ($ datalist as $ num)
{
$ T = "";
$ Num = intval ($ num );
If ($ num = 0) continue;
While ($ num> 0)
{
$ T = $ arr [$ num % $ bin]. $ t;
$ Num = floor ($ num/$ bin );
}
$ Tlen = strlen ($ t );
If ($ tlen % $ bytelen! = 0)
{
$ Pad_len = $ bytelen-$ tlen % $ bytelen;
$ T = str_pad ("", $ pad_len, "0", STR_PAD_LEFT). $ t; // The length of less than one byte is automatically increased to 0.
}
$ AOutChar [] = $ t;
}
Return $ aOutChar;
}
X-Powered-By: PHP/5.2.0
Content-type: text/html
Array (3 ){
[0] =>
Int (255)
[1] =>
Int (65331)
[2] =>
Int (52275)
}
Array (2 ){
[0] =>
Int (124)
[1] =>
Int (508)
}
Array (2 ){
[0] =>
Int (342099)
[1] =>
Int (5345)
}
Later, these are just implementation methods. In fact, they do not care about php or other languages, and the implementation ideas are the same. Php actually has many built-in functions to accomplish this:
Bindec (), decoct (), dechex () base_convert () decbin () is just the implementation idea here. Haha!
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.