- miguelmota / util.php
- hex2bin
- Parameters
- Return Values
- Errors/Exceptions
- Examples
- See Also
- User Contributed Notes 13 notes
- Programming-Idioms
- Idiom #176 Hex string to byte array
- Please choose a nickname before doing this
- How can I convert a hex string to a byte array in php
- Share solution ↓
- Additional Information:
- Didn't find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- PHP
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
- PHP hex2bin() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
miguelmota / util.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
function string2ByteArray ( $ string ) |
return unpack( ‘C*’ , $ string ); |
> |
function byteArray2String ( $ byteArray ) |
$ chars = array_map(» chr «, $ byteArray ); |
return join( $ chars ); |
> |
function byteArray2Hex ( $ byteArray ) |
$ chars = array_map(» chr «, $ byteArray ); |
$ bin = join( $ chars ); |
return bin2hex( $ bin ); |
> |
function hex2ByteArray ( $ hexString ) |
$ string = hex2bin( $ hexString ); |
return unpack( ‘C*’ , $ string ); |
> |
function string2Hex ( $ string ) |
return bin2hex( $ string ); |
> |
function hex2String ( $ hexString ) |
return hex2bin( $ hexString ); |
> |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
include ( ‘./util.php’ ); |
$ byteArray = unpack( ‘C*’ , ‘hello’ ); |
assert(string2ByteArray( ‘hello’ ) == $ byteArray ); |
assert(byteArray2String( $ byteArray ) == ‘hello’ ); |
assert(byteArray2Hex( $ byteArray ) == ‘68656c6c6f’ ); |
assert(hex2ByteArray( ‘68656c6c6f’ ) == $ byteArray ); |
assert(string2Hex( ‘hello’ ) == ‘68656c6c6f’ ); |
assert(hex2String( ‘68656c6c6f’ ) == ‘hello’ ); |
?> |
hex2bin
This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.
Parameters
Hexadecimal representation of data.
Return Values
Returns the binary representation of the given data or false on failure.
Errors/Exceptions
If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.
Examples
Example #1 hex2bin() example
The above example will output something similar to:
string(16) "example hex data"
See Also
- bin2hex() — Convert binary data into hexadecimal representation
- unpack() — Unpack data from binary string
User Contributed Notes 13 notes
The function hex2bin does not exist in PHP5.
You can use ‘pack’ instead :
$binary_string = pack(«H*» , $hex_string);
if you want to convert a hex encoded string to a binary string without any notices/errors regardless of the input, use this function:
function hex2binary ( $str )
return ctype_xdigit ( strlen ( $str ) % 2 ? «» : $str ) ? hex2bin ( $str ) : false ;
>
hex2binary ( «» ); // false
hex2binary ( «a» ); // false
hex2binary ( «ab» ); // binary-string
?>
if the return type is string, you have your binary-string. otherwise (bool) false.
I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don’t need to worry about upgrading php because when it is upgraded, it will use the build in function.
if ( ! function_exists ( ‘hex2bin’ ) ) function hex2bin ( $str ) $sbin = «» ;
$len = strlen ( $str );
for ( $i = 0 ; $i < $len ; $i += 2 ) $sbin .= pack ( "H*" , substr ( $str , $i , 2 ) );
>
The function pack(«H*» , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.
#error:
hex2bin(): Hexadecimal input string must have an even length
For those who are facing the error above trying to convert hex to bin. you can pad your hex string with initial 0 before hex2bin.
function hexPad(string $hex_string)
$st_l = strlen($hex_string);
return str_pad($hex_string, $st_l + ($st_l % 2), ‘0’, STR_PAD_LEFT);
>
for usage hex2bin(hexPad(‘1bc’));
If you want to convert hex to GUID format (In my case, it was to convert GUID from MSSQL database) :
function hex2Guid ( $hex )
$hex = [
substr ( $hex , 0 , 8 ),
substr ( $hex , 8 , 4 ),
substr ( $hex , 12 , 4 ),
substr ( $hex , 16 , 4 ),
substr ( $hex , 20 ),
];
$order [ 0 ] = [ 6 , 7 , 4 , 5 , 2 , 3 , 0 , 1 ];
$order [ 1 ] = [ 2 , 3 , 0 , 1 ];
$order [ 2 ] = [ 2 , 3 , 0 , 1 ];
$order [ 3 ] = [ 0 , 1 , 2 , 3 ];
$order [ 4 ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ];
return strtoupper ( $result );
>
Example :
echo hex2Guid ( «64d3938b7008cd4bad5ffe56755d163f» );
Case of an incomplete hex string following function may help:
function make2validhex ( $data ) $data = (string) $data ;
$len = strlen ( $data );
if( $len % 2 ) return substr ( $data , 0 , $len — 1 );
>
return $data ;
>
?>
test:
$string = «not complete» ;
echo $string ;
echo PHP_EOL ;
$hex = bin2hex ( $string ); //»6e6f7420636f6d706c657465″
echo $hex ;
echo PHP_EOL ;
$deff = substr ( $hex , 0 , strlen ( $hex ) — 1 ); //»6e6f7420636f6d706c65746″
echo $deff ;
echo PHP_EOL ;
echo hex2bin ( make2validhex ( $deff )); //»not complet»
echo PHP_EOL ;
?>
For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.
function hextobin ( $hexstr )
<
$n = strlen ( $hexstr );
$sbin = «» ;
$i = 0 ;
while( $i < $n )
<
$a = substr ( $hexstr , $i , 2 );
$c = pack ( «H*» , $a );
if ( $i == 0 ) < $sbin = $c ;>
else < $sbin .= $c ;>
$i += 2 ;
>
return $sbin ;
>
?>
A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.
if (! function_exists ( ‘hex2bin’ )) function hex2bin ( $data ) static $old ;
if ( $old === null ) $old = version_compare ( PHP_VERSION , ‘5.2’ , ‘ >
$isobj = false ;
if ( is_scalar ( $data ) || (( $isobj = is_object ( $data )) && method_exists ( $data , ‘__toString’ ))) if ( $isobj && $old ) ob_start ();
echo $data ;
$data = ob_get_clean ();
>
else $data = (string) $data ;
>
>
else trigger_error ( __FUNCTION__ . ‘() expects parameter 1 to be string, ‘ . gettype ( $data ) . ‘ given’ , E_USER_WARNING );
return; //null in this case
>
$len = strlen ( $data );
if ( $len % 2 ) trigger_error ( __FUNCTION__ . ‘(): Hexadecimal input string must have an even length’ , E_USER_WARNING );
return false ;
>
if ( strspn ( $data , ‘0123456789abcdefABCDEF’ ) != $len ) trigger_error ( __FUNCTION__ . ‘(): Input string must be hexadecimal string’ , E_USER_WARNING );
return false ;
>
return pack ( ‘H*’ , $data );
>
>
?>
$test = bin2hex(‘sample . ‘);
echo _hex2bin($test);
// another hex2bin replacement
function _hex2bin($result) $out = »;
for($c=0;$c
return (string) $out;
>
A way to convert hex strings in the form «0x123ABC» to integer is to use the function base_convert(«0x123ABC», 16, 10)
function Hex2Bin($data) $BinData = «»;
for ($i=0;$i
return $BinData;
Programming-Idioms
- C
- C++
- C#
- Go
- Java
- JS
- Obj-C
- PHP
- Python
- Ruby
- Rust
- Or search :
Idiom #176 Hex string to byte array
From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
$a = array_map('hexdec', str_split($s, 2));
const char* hexstring = "deadbeef"; size_t length = sizeof(hexstring); unsigned char bytearray[length / 2]; for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2) bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25;
byte[] a = new byte[s.Length/2]; for (int i = 0, h = 0; h
import std.algorithms; import std.array; import std.conv; import std.range;
ubyte[] a = s.chunks(2) .map!(digits => digits.to!ubyte) .array;
import std.conv; import std.string;
ubyte[] a = cast(ubyte[]) hexString!s.representation;
import 'package:convert/convert.dart';
use iso_c_binding, only : c_int8_t
integer(kind=c_int8_t), dimension(:), allocatable :: a allocate (a(len(s)/2)) read(unit=s,fmt='(*(Z2))') a
a, err := hex.DecodeString(s) if err != nil
s .split('') .map((el, ix, arr) => ix % 2 ? null : el + arr[ix + 1]) .filter(el => el !== null) .map(x => parseInt(x, 16))
import java.math.BigInteger;
byte[] a = new BigInteger(s, 16).toByteArray();
public static byte[] hexToByteArray(String s) < int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) < data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) return data; >
for i := 0 to length(s) div 2 - 1 do a[i] := StrToInt('$'+Copy(s,2*(i)+1,2));
let a: Vec = Vec::from_hex(s).expect("Invalid Hex String");
let a: Vec = decode(s).expect("Hex string should be valid");
use data_encoding::HEXLOWER_PERMISSIVE;
let a: Vec = HEXLOWER_PERMISSIVE.decode(&s.into_bytes()).unwrap();
Please choose a nickname before doing this
$a = array_map('hexdec', str_split($s, 2));
const char* hexstring = "deadbeef"; size_t length = sizeof(hexstring); unsigned char bytearray[length / 2]; for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2) bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25;
byte[] a = new byte[s.Length/2]; for (int i = 0, h = 0; h
ubyte[] a = s.chunks(2) .map!(digits => digits.to!ubyte) .array;
ubyte[] a = cast(ubyte[]) hexString!s.representation;
integer(kind=c_int8_t), dimension(:), allocatable :: a allocate (a(len(s)/2)) read(unit=s,fmt='(*(Z2))') a
a, err := hex.DecodeString(s) if err != nil
s .split('') .map((el, ix, arr) => ix % 2 ? null : el + arr[ix + 1]) .filter(el => el !== null) .map(x => parseInt(x, 16))
byte[] a = new BigInteger(s, 16).toByteArray();
public static byte[] hexToByteArray(String s) < int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) < data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) return data; >
for i := 0 to length(s) div 2 - 1 do a[i] := StrToInt('$'+Copy(s,2*(i)+1,2));
let a: Vec = Vec::from_hex(s).expect("Invalid Hex String");
let a: Vec = decode(s).expect("Hex string should be valid");
let a: Vec = HEXLOWER_PERMISSIVE.decode(&s.into_bytes()).unwrap();
How can I convert a hex string to a byte array in php
Below is the c# implementation
using System; public class Program < void CanDecodeFromString(string str) < if (str.Length % 2 != 0) return; //OutputText(" " + "J1939:" + "\r\n"); byte[] j1939data = new byte[str.Length / 2]; for (int i = 0; i < str.Length / 2; i++) < j1939data[i] = System.Convert.ToByte(str.Substring(2 * i, 2), 16); >//J1939DataDecode(j1939data); Console.WriteLine(String.Join("\n", j1939data)); > public static void Main() < var p= new Program(); p.CanDecodeFromString("31058F410C15E1310D48312F8F41310000630220290082"); Console.WriteLine("Hello World"); >>
hex_string="31058F410C15E1310D48312F8F41310000630220290082" hex_data = hex_string.decode("hex") import array array.array('B', hex_data)
In php what is the proper way for it ?
49 5 143 65 12 21 225 49 13 72 49 47 143 65 49 0 0 99 2 32 41 0 130
Share solution ↓
Additional Information:
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
PHP hex2bin() Function
The hex2bin() function converts a string of hexadecimal values to ASCII characters.
Syntax
Parameter Values
Technical Details
Return Value: | Returns the ASCII character of the converted string, or FALSE on failure |
---|---|
PHP Version: | 5.4.0+ |
Changelog: | PHP 5.5.1 - Throws a warning if the string is invalid hexadecimal string. PHP 5.4.1 - Throws a warning if the string is of odd length. In 5.4.0, the string was silently accepted, but the last byte was removed. |
❮ PHP String Reference
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.