/* -*- 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 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; }