Saturday, October 24, 2020

From IP to Hex and back again

 Did a one-liner to convert an IP address as a string into a string with 4 hex number pairs.

hexip=$(echo $ip | awk -F '.' '{printf "%02x%02x%02x%02x\n", $1,$2,$3,$4}')

Then from this string back to an IP address.

echo $hexip | grep -Eo '[A-Za-z0-9]{2}' | paste -s | awk -F '\t' '{printf "%d.%d.%d.%d","0x"$1,"0x"$2,"0x"$3,"0x"$4}'

Edit: It has occurred to me that given the fixed nature of the hexip string (it is always character pairs) there is no reason to grep and paste before using awk. Instead, this can all be done with one awk program.

echo $hexip | awk -F " " '{gsub(/../,"& "); printf "%d.%d.%d.%d","0x"$1,"0x"$2,"0x"$3,"0x"$4}'

No comments:

Post a Comment

 RasPi Pico and an OLED Screen My project for this morning was to connect a small I2C OLED screen to Raspberry Pi Pico and make it do someth...