1

I can find seemingly every variation of hex manipulation by printf except this one.

I am trying to send html hex colour values to a text file, built mostly using printf.

I can calculate the separate R, G and B values but they normally print in decimal (range 0-255). How can I print them out, a) in two-digit hexadecimal and b) concatenated as a six-digit string?

For example variable values $R=254, $G=127, $B=0 should print as FE7F00.

1 Answer 1

4

You can use printf's %x (lowercase) or %X (uppercase) for this, forcing the width to 2 characters:

#!/bin/sh

r=254
g=127
b=0

printf '%02X%02X%02X\n' "$r" "$g" "$b"

The result looks like so:

FE7F00
1
  • Thank you, that does the trick. Never thought to specify %02X three times in a row. Aug 7, 2020 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .