Skip to content

conv

A library of conversion related functions.

lb_hex_to_rgb hex

Return an rgb number from a hexidecimal number.

Parameters:
Name Type Description Default
hex hex hexidecimal number to be converted to rgb required
Examples:
#!/usr/bin/env bash

# shellcheck source=/dev/null
source ../init
source "${LIBBASH_DIR}/conv"

function main() {
  hex="#FFFFFF"
  printf 'hex: %s\n' "${hex}"
  s=$(lb_hex_to_rgb "${hex}")
  printf 'lb_hex_to_rgb: %s\n' "${s}"

  rgb=(255 255 255)
  printf 'rgb: %s\n' "${rgb[@]}"
  s=$(lb_rgb_to_hex "${rgb[@]}")
  printf 'lb_rgb_to_hex: %s\n' "${s}"
}

main "${@}"
Show source code in conv
#!/usr/bin/env bash
: "${LIBBASH_DIR:?LIBBASH_DIR must be set. Please source libbash/init before other libraries.}"

#------------------------------ Global Variables ------------------------------

#------------------------------ Private Functions -----------------------------

#------------------------------ Public Functions ------------------------------

function lb_hex_to_rgb() {
  lb_check_args_num "${@}" 1
  : "${1/\#}"
  ((r=16#${_:0:2},g=16#${_:2:2},b=16#${_:4:2}))
  printf '%s\n' "$r $g $b"
}

function lb_rgb_to_hex() {
  lb_check_args_num "${@}" 3
  printf '#%02x%02x%02x\n' "$1" "$2" "$3"
}

lb_rgb_to_hex r g b

Return a lower case hexidecimal number prefixed with a pound symbol.

Parameters:
Name Type Description Default
r int red value from 0 to 255 required
g int green value from 0 to 255 required
b int blue value from 0 to 255 required
Examples:
#!/usr/bin/env bash

# shellcheck source=/dev/null
source ../init
source "${LIBBASH_DIR}/conv"

function main() {
  hex="#FFFFFF"
  printf 'hex: %s\n' "${hex}"
  s=$(lb_hex_to_rgb "${hex}")
  printf 'lb_hex_to_rgb: %s\n' "${s}"

  rgb=(255 255 255)
  printf 'rgb: %s\n' "${rgb[@]}"
  s=$(lb_rgb_to_hex "${rgb[@]}")
  printf 'lb_rgb_to_hex: %s\n' "${s}"
}

main "${@}"
Show source code in conv
#!/usr/bin/env bash
: "${LIBBASH_DIR:?LIBBASH_DIR must be set. Please source libbash/init before other libraries.}"

#------------------------------ Global Variables ------------------------------

#------------------------------ Private Functions -----------------------------

#------------------------------ Public Functions ------------------------------

function lb_hex_to_rgb() {
  lb_check_args_num "${@}" 1
  : "${1/\#}"
  ((r=16#${_:0:2},g=16#${_:2:2},b=16#${_:4:2}))
  printf '%s\n' "$r $g $b"
}

function lb_rgb_to_hex() {
  lb_check_args_num "${@}" 3
  printf '#%02x%02x%02x\n' "$1" "$2" "$3"
}