From 532b58ce2ed2d03ea1497c2ff5112e6858d437d2 Mon Sep 17 00:00:00 2001 From: Natalia Portillo Date: Thu, 17 Oct 2019 22:11:57 +0100 Subject: [PATCH] Add function to convert a hex string to binary. --- CMakeLists.txt | 2 +- dicmote.h | 4 ++++ hex2bin.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 hex2bin.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c25698..be6655b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ project(dicremote C) set(CMAKE_C_STANDARD 90) -set(MAIN_SOURCES main.c list_devices.c device.c scsi.c) +set(MAIN_SOURCES main.c list_devices.c device.c scsi.c hex2bin.c) if("${CMAKE_SYSTEM}" MATCHES "Linux") set(PLATFORM_SOURCES linux/list_devices.c linux/linux.h linux/device.c linux/scsi.c) diff --git a/dicmote.h b/dicmote.h index 7322414..f094eaa 100644 --- a/dicmote.h +++ b/dicmote.h @@ -18,7 +18,9 @@ #ifndef DICMOTE_H #define DICMOTE_H +#include #include + #define DICMOTE_NAME "DiscImageChef Remote Server" #define DICMOTE_VERSION "0.99" #define DICMOTE_PORT 6666 @@ -401,5 +403,7 @@ int32_t SendScsiCommand(int device_fd, uint32_t cdb_len, uint32_t* buf_len, uint32_t* sense_len); +int hexchr2bin(const char hex, char* out); +size_t hexs2bin(const char* hex, unsigned char** out); #endif diff --git a/hex2bin.c b/hex2bin.c new file mode 100644 index 0000000..548b8c9 --- /dev/null +++ b/hex2bin.c @@ -0,0 +1,60 @@ +/* + * This file is part of the DiscImageChef Remote Server. + * Copyright (c) 2019 Natalia Portillo. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program 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 + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +int hexchr2bin(const char hex, char* out) +{ + if(out == NULL) return 0; + + if(hex >= '0' && hex <= '9') + *out = hex - '0'; + else if(hex >= 'A' && hex <= 'F') + *out = hex - 'A' + 10; + else if(hex >= 'a' && hex <= 'f') + *out = hex - 'a' + 10; + else + return 0; + + return 1; +} + +size_t hexs2bin(const char* hex, unsigned char** out) +{ + size_t len; + char b1; + char b2; + size_t i; + + if(hex == NULL || *hex == '\0' || out == NULL) return 0; + + len = strlen(hex); + if(len % 2 != 0) return 0; + len /= 2; + + *out = malloc(len); + memset(*out, 'A', len); + for(i = 0; i < len; i++) + { + if(!hexchr2bin(hex[i * 2], &b1) || !hexchr2bin(hex[i * 2 + 1], &b2)) return 0; + + (*out)[i] = (b1 << 4) | b2; + } + return len; +} \ No newline at end of file