search
HomeBackend DevelopmentPHP Problemphp convert string to hexadecimal

In the field of web development, it is often necessary to encode and decode data. Among them, converting strings to hexadecimal is a common requirement. For example, when encrypting, transmitting, or storing data, the data needs to be converted to hexadecimal format. In PHP, it is also very convenient to convert into functions. Let’s introduce the specific implementation method.

1. Use the bin2hex() function

PHP provides the bin2hex() function, through which binary data can be converted into a hexadecimal string. Since strings are essentially binary data, we can first convert the string that needs to be converted into binary format, and then use the bin2hex() function to convert the string into hexadecimal. The specific code is as follows:

$str = 'hello world';
$hex_str = bin2hex($str); 
echo $hex_str;

In the above code, the string "hello world" is converted into a binary string, and then converted into a hexadecimal string through the bin2hex() function. The final output result is:

68656c6c6f20776f726c64

This result looks strange, but it is actually the hexadecimal representation of "hello world". Every two characters correspond to one byte, making it easy for further processing and transmission.

2. Custom function to convert string to hexadecimal

In addition to using built-in functions, we can also use custom functions to convert strings to hexadecimal. A simple implementation code is provided below:

function str2hex($str) {
    $hex='';
    for ($i=0; $i<strlen($str); $i++) {
        $ord=ord($str[$i]);
        $hexCode=dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return $hex;
}

$str = 'hello world';
$hex_str = str2hex($str);
echo $hex_str;

In the above code, we first define a custom function str2hex(), which can convert a string to hexadecimal format. The specific implementation principle is as follows:

  1. Traverse the string and use the ord() function to convert each character into ASCII code.
  2. Convert ASCII code to hexadecimal format using the dechex() function.
  3. When the currently obtained hexadecimal digit is less than two digits, add zeros in front.
  4. Splice the hexadecimal format of each character together to finally get the hexadecimal format of the entire string.

The output result is the same as the result of using the built-in function bin2hex(), both are:

68656c6c6f20776f726c64

Summary

In PHP, convert the string to hexadecimal There are two main ways to implement hex format: using the built-in function bin2hex() or a custom function. Among them, it is easier to use built-in functions, but custom functions have higher flexibility and can perform more customized calculations and conversions. Developers can choose a suitable method to implement based on their actual needs.

The above is the detailed content of php convert string to hexadecimal. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool