summaryrefslogtreecommitdiff
path: root/src/asc2bin.cc
blob: da424a62c5fc5674ea8e259913da3ea425a53686 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set et sw=2 ts=2: */
/***************************************************************************
 *            asc2bin.cc
 *
 *  Thu Sep  5 11:12:50 CEST 2013
 *  Copyright 2013 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *  This file is part of lrtp.
 *
 * lrtp is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * lrtp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with lrtp; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
#include "asc2bin.h"

#include <string.h>

static int asc2nibble(unsigned char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 0xa;
	if(c >= 'A' && c <= 'F') return c - 'A' + 0xa;
	return -1;
}

ssize_t asc2bin(char *raw, size_t rawsz, const char *hex, size_t hexlen)
{
  if(hexlen % 2 != 0) return -1;
  if(rawsz < hexlen / 2) return -1;

  unsigned char val;
  int nibble;
  size_t size = 0;

  while(size < hexlen / 2) {
    nibble = asc2nibble(hex[0]);
    if(nibble == -1) return -1;
    val = (nibble << 4);

    nibble = asc2nibble(hex[1]);
    if(nibble == -1) return -1;
    val |= (nibble & 0xff);

    *raw = val;
    raw++;
    size++;

    hex += 2;
  }

  return (ssize_t)size;
}