Add function to convert a hex string to binary.

This commit is contained in:
2019-10-17 22:11:57 +01:00
parent 18f7dda4f8
commit 532b58ce2e
3 changed files with 65 additions and 1 deletions

View File

@@ -3,7 +3,7 @@ project(dicremote C)
set(CMAKE_C_STANDARD 90) 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") if("${CMAKE_SYSTEM}" MATCHES "Linux")
set(PLATFORM_SOURCES linux/list_devices.c linux/linux.h linux/device.c linux/scsi.c) set(PLATFORM_SOURCES linux/list_devices.c linux/linux.h linux/device.c linux/scsi.c)

View File

@@ -18,7 +18,9 @@
#ifndef DICMOTE_H #ifndef DICMOTE_H
#define DICMOTE_H #define DICMOTE_H
#include <stddef.h>
#include <stdint.h> #include <stdint.h>
#define DICMOTE_NAME "DiscImageChef Remote Server" #define DICMOTE_NAME "DiscImageChef Remote Server"
#define DICMOTE_VERSION "0.99" #define DICMOTE_VERSION "0.99"
#define DICMOTE_PORT 6666 #define DICMOTE_PORT 6666
@@ -401,5 +403,7 @@ int32_t SendScsiCommand(int device_fd,
uint32_t cdb_len, uint32_t cdb_len,
uint32_t* buf_len, uint32_t* buf_len,
uint32_t* sense_len); uint32_t* sense_len);
int hexchr2bin(const char hex, char* out);
size_t hexs2bin(const char* hex, unsigned char** out);
#endif #endif

60
hex2bin.c Normal file
View File

@@ -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 <http://www.gnu.org/licenses/>.
*/
#include <malloc.h>
#include <stddef.h>
#include <string.h>
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;
}