Programming with Hexadecimal
📚 14 min read
🎯 Intermediate-Advanced
📅 Updated: 2024
Python Hex Encoding
Python provides native hex encoding through built-in methods:
String to Hex
# Method 1: Using bytes.hex() text = "Hello World" hex_encoded = text.encode().hex() print(hex_encoded) # "48656c6c6f20576f726c64" # Method 2: Manual conversion hex_encoded = ''.join(f'{ord(c):02x}' for c in text) # Method 3: Using binascii import binascii hex_encoded = binascii.hexlify(text.encode()).decode()
Hex to String
# Method 1: Using bytes.fromhex() hex_string = "48656c6c6f20576f726c64" decoded = bytes.fromhex(hex_string).decode('utf-8') print(decoded) # "Hello World" # Method 2: Using binascii import binascii decoded = binascii.unhexlify(hex_string).decode('utf-8') # With error handling try: decoded = bytes.fromhex(hex_string).decode('utf-8') except (ValueError, UnicodeDecodeError) as e: print(f"Decode error: {e}")
File Hex Encoding
# Read binary file and convert to hex with open('input.bin', 'rb') as f: binary_data = f.read() hex_data = binary_data.hex() # Write hex to file with open('output.hex', 'w') as f: f.write(hex_data) # Decode hex file back to binary with open('output.hex', 'r') as f: hex_data = f.read() binary_data = bytes.fromhex(hex_data) with open('restored.bin', 'wb') as f: f.write(binary_data)
JavaScript Hex Encoding
Browser (Modern)
// String to Hex (UTF-8) function stringToHex(str) { const encoder = new TextEncoder(); const bytes = encoder.encode(str); return Array.from(bytes, b => b.toString(16).padStart(2, '0') ).join(''); } // Hex to String (UTF-8) function hexToString(hex) { const bytes = hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16) ); const decoder = new TextDecoder(); return decoder.decode(new Uint8Array(bytes)); } // Usage const encoded = stringToHex("Hello"); // "48656c6c6f" const decoded = hexToString(encoded); // "Hello"
Node.js
// String to Hex const hex = Buffer.from("Hello", 'utf8').toString('hex'); console.log(hex); // "48656c6c6f" // Hex to String const text = Buffer.from("48656c6c6f", 'hex').toString('utf8'); console.log(text); // "Hello" // File operations const fs = require('fs'); // Read file as hex const buffer = fs.readFileSync('file.bin'); const hex = buffer.toString('hex'); // Write hex to file fs.writeFileSync('file.hex', hex); // Restore from hex const hexContent = fs.readFileSync('file.hex', 'utf8'); const binary = Buffer.from(hexContent, 'hex'); fs.writeFileSync('restored.bin', binary);
Java Hex Encoding
import java.nio.charset.StandardCharsets; public class HexEncoder { // String to Hex public static String toHex(String text) { byte[] bytes = text.getBytes(StandardCharsets.UTF_8); StringBuilder hex = new StringBuilder(); for (byte b : bytes) { hex.append(String.format("%02x", b)); } return hex.toString(); } // Hex to String public static String fromHex(String hex) { int length = hex.length(); byte[] bytes = new byte[length / 2]; for (int i = 0; i < length; i += 2) { bytes[i / 2] = (byte) Integer.parseInt( hex.substring(i, i + 2), 16 ); } return new String(bytes, StandardCharsets.UTF_8); } // Usage public static void main(String[] args) { String text = "Hello"; String hex = toHex(text); System.out.println(hex); // "48656c6c6f" String decoded = fromHex(hex); System.out.println(decoded); // "Hello" } } // Using Apache Commons Codec (cleaner) import org.apache.commons.codec.binary.Hex; String hex = Hex.encodeHexString("Hello".getBytes()); String text = new String(Hex.decodeHex(hex));
C++ Hex Encoding
#include <iostream> #include <string> #include <sstream> #include <iomanip> // String to Hex std::string toHex(const std::string& input) { std::ostringstream hex; hex << std::hex << std::setfill('0'); for (unsigned char c : input) { hex << std::setw(2) << static_cast(c); } return hex.str(); } // Hex to String std::string fromHex(const std::string& hex) { std::string result; for (size_t i = 0; i < hex.length(); i += 2) { std::string byte = hex.substr(i, 2); char c = static_cast ( std::stoi(byte, nullptr, 16) ); result += c; } return result; } // Usage int main() { std::string text = "Hello"; std::string hex = toHex(text); std::cout << hex << std::endl; // "48656c6c6f" std::string decoded = fromHex(hex); std::cout << decoded << std::endl; // "Hello" return 0; }
PHP Hex Encoding
<?php // String to Hex $text = "Hello"; $hex = bin2hex($text); echo $hex; // "48656c6c6f" // Hex to String $decoded = hex2bin($hex); echo $decoded; // "Hello" // URL hex encoding (percent-encoding) $encoded = urlencode("Hello World"); echo $encoded; // "Hello+World" $decoded = urldecode($encoded); echo $decoded; // "Hello World" // Custom hex encoding function function stringToHex($string) { $hex = ''; for ($i = 0; $i < strlen($string); $i++) { $hex .= sprintf("%02x", ord($string[$i])); } return $hex; } function hexToString($hex) { $string = ''; for ($i = 0; $i < strlen($hex); $i += 2) { $string .= chr(hexdec(substr($hex, $i, 2))); } return $string; } ?>
Go (Golang) Hex Encoding
package main import ( "encoding/hex" "fmt" ) func main() { // String to Hex text := "Hello" encoded := hex.EncodeToString([]byte(text)) fmt.Println(encoded) // "48656c6c6f" // Hex to String decoded, err := hex.DecodeString(encoded) if err != nil { fmt.Println("Decode error:", err) return } fmt.Println(string(decoded)) // "Hello" // With error handling hexStr := "48656c6c6f" if len(hexStr)%2 != 0 { fmt.Println("Invalid hex: odd length") return } bytes, err := hex.DecodeString(hexStr) if err != nil { fmt.Println("Decode error:", err) return } result := string(bytes) fmt.Println(result) }
Ruby Hex Encoding
# String to Hex text = "Hello" hex = text.unpack('H*').first puts hex # "48656c6c6f" # Hex to String decoded = [hex].pack('H*') puts decoded # "Hello" # Alternative methods hex = text.bytes.map { |b| "%02x" % b }.join decoded = hex.scan(/../).map { |x| x.hex.chr }.join # File operations hex = File.binread('file.bin').unpack('H*').first File.write('file.hex', hex) # Restore from hex hex_content = File.read('file.hex') binary = [hex_content].pack('H*') File.binwrite('restored.bin', binary)
C# Hex Encoding
using System; using System.Text; class HexEncoder { // String to Hex public static string ToHex(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text); return BitConverter.ToString(bytes) .Replace("-", "").ToLower(); } // Hex to String public static string FromHex(string hex) { byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte( hex.Substring(i * 2, 2), 16 ); } return Encoding.UTF8.GetString(bytes); } // Usage static void Main() { string text = "Hello"; string hex = ToHex(text); Console.WriteLine(hex); // "48656c6c6f" string decoded = FromHex(hex); Console.WriteLine(decoded); // "Hello" } }
Best Practices Across Languages
- Use Built-in Functions: Prefer language standard libraries over custom implementations
- Handle Encoding: Always specify UTF-8 for text encoding
- Validate Input: Check for even-length hex strings and valid characters
- Error Handling: Use try-catch blocks for decode operations
- Performance: For large files, use streaming/chunked processing
- Security: Never execute decoded hex data without validation
💡 Development Tip
Test your code with our hex decoder tool before deployment. Verify edge cases like empty strings, special characters, and large files.