hex-dec.c revision c579e4abcb05c1a28bad3e2c6a240fd31b5b567a
02c335c23bf5fa225a467c19f2c063fb0dc7b8c3Timo Sirainen/* Copyright (c) 2005-2011 Dovecot authors, see the included COPYING file */
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch#include "lib.h"
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch#include "hex-dec.h"
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Boschvoid dec2hex(unsigned char *hexstr, uintmax_t dec, unsigned int hexstr_size)
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch{
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch unsigned int i;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch for (i = 0; i < hexstr_size; i++) {
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch unsigned int value = dec & 0x0f;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch if (value < 10)
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch hexstr[hexstr_size-i-1] = value + '0';
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch else
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch hexstr[hexstr_size-i-1] = value - 10 + 'A';
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch dec >>= 4;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch }
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch}
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Boschuintmax_t hex2dec(const unsigned char *data, unsigned int len)
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch{
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch unsigned int i;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch uintmax_t value = 0;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch for (i = 0; i < len; i++) {
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch value = value*0x10;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch if (data[i] >= '0' && data[i] <= '9')
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch value += data[i]-'0';
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch else if (data[i] >= 'A' && data[i] <= 'F')
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch value += data[i]-'A' + 10;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch else if (data[i] >= 'a' && data[i] <= 'f')
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch value += data[i]-'a' + 10;
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch else
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch return 0;
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch }
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch return value;
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch}
2f64a4c88de91c483fb378bc80d10e1caa6f2305Stephan Bosch
3fcb3d2d1f3583025ff62bae95ec706920f398b1Stephan Bosch