Conversion Techniques
Command-Line Conversion Methods
Using xxd
Command
xxd
is a powerful tool for hex conversion in Linux:
## Convert hex to ASCII
echo -n "48 65 6c 6c 6f" | xxd -r -p
## Output: Hello
## Convert ASCII to hex
echo -n "Hello" | xxd -p
## Output: 48656c6c6f
Using printf
Command
printf
provides flexible hex-to-ASCII conversion:
## Convert single hex value
printf "\x48\x65\x6c\x6c\x6f"
## Output: Hello
## Hex to decimal conversion
printf "%d" 0x41
## Output: 65
Bash Scripting Conversion Functions
Hex to ASCII Function
hex_to_ascii() {
echo "$1" | sed 's/\(..\)/\\x\1/g' | xargs printf
}
## Usage example
hex_to_ascii "48 65 6c 6c 6f"
## Output: Hello
ASCII to Hex Function
ascii_to_hex() {
echo -n "$1" | od -A n -t x1 | tr -d ' \n'
}
## Usage example
ascii_to_hex "Hello"
## Output: 48656c6c6f
Advanced Conversion Techniques
graph TD
A[Hex Input] --> B{Conversion Method}
B --> |xxd| C[ASCII Output]
B --> |printf| D[ASCII/Decimal Output]
B --> |Custom Function| E[Flexible Conversion]
Conversion Method Comparison
Method |
Pros |
Cons |
xxd |
Built-in, versatile |
Limited complex parsing |
printf |
Direct conversion |
Less readable |
Bash Func |
Customizable, flexible |
Requires scripting |
Error Handling Considerations
## Validate hex input
is_valid_hex() {
[[ "$1" =~ ^[0-9A-Fa-f]+$ ]] && return 0 || return 1
}
## Example usage
if is_valid_hex "48656C6C6F"; then
echo "Valid hex input"
else
echo "Invalid hex input"
fi
At LabEx, we emphasize practical, robust conversion techniques that empower Linux system programmers to handle diverse encoding challenges efficiently.