bcb4e51a409d94ae670de96afb8483a4f7855294Stephan Bosch/* Copyright (c) 2005-2018 Dovecot authors, see the included COPYING file */
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen#include "lib.h"
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen#include "hex-dec.h"
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainenvoid dec2hex(unsigned char *hexstr, uintmax_t dec, unsigned int hexstr_size)
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen{
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen unsigned int i;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen for (i = 0; i < hexstr_size; i++) {
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen unsigned int value = dec & 0x0f;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen if (value < 10)
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen hexstr[hexstr_size-i-1] = value + '0';
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen else
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen hexstr[hexstr_size-i-1] = value - 10 + 'A';
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen dec >>= 4;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen }
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen}
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainenuintmax_t hex2dec(const unsigned char *data, unsigned int len)
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen{
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen unsigned int i;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen uintmax_t value = 0;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen for (i = 0; i < len; i++) {
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen value = value*0x10;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen if (data[i] >= '0' && data[i] <= '9')
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen value += data[i]-'0';
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen else if (data[i] >= 'A' && data[i] <= 'F')
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen value += data[i]-'A' + 10;
c579e4abcb05c1a28bad3e2c6a240fd31b5b567aTimo Sirainen else if (data[i] >= 'a' && data[i] <= 'f')
c579e4abcb05c1a28bad3e2c6a240fd31b5b567aTimo Sirainen value += data[i]-'a' + 10;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen else
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen return 0;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen }
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen return value;
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen}
e6055ac974358d31bb2269731dcac57fbe910cc2Timo Sirainen