Related
I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.
Have you tried strtol()?
strtol - convert string to a long integer
Example:
const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);
In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:
const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);
(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)
Or if you want to have your own implementation, I wrote this quick function as an example:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Something like this could be useful:
char str[] = "0x1800785";
int num;
sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num);
Read man sscanf
Assuming you mean it's a string, how about strtol?
Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.
#include <inttypes.h>
/**
* xtou64
* Take a hex string and convert it to a 64bit number (max 16 hex digits).
* The string must only contain digits and valid hex characters.
*/
uint64_t xtou64(const char *str)
{
uint64_t res = 0;
char c;
while ((c = *str++)) {
char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
res = (res << 4) | (uint64_t) v;
}
return res;
}
The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.
One quick & dirty solution:
// makes a number from two ascii hexa characters
int ahex2int(char a, char b){
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
return (a << 4) + b;
}
You have to be sure your input is correct, no validation included (one could say it is C). Good thing it is quite compact, it works with both 'A' to 'F' and 'a' to 'f'.
The approach relies on the position of alphabet characters in the ASCII table, let's peek e.g. to Wikipedia (https://en.wikipedia.org/wiki/ASCII#/media/File:USASCII_code_chart.png). Long story short, the numbers are below the characters, so the numeric characters (0 to 9) are easily converted by subtracting the code for zero. The alphabetic characters (A to F) are read by zeroing other than last three bits (effectively making it work with either upper- or lowercase), subtracting one (because after the bit masking, the alphabet starts on position one) and adding ten (because A to F represent 10th to 15th value in hexadecimal code). Finally, we need to combine the two digits that form the lower and upper nibble of the encoded number.
Here we go with same approach (with minor variations):
#include <stdio.h>
// takes a null-terminated string of hexa characters and tries to
// convert it to numbers
long ahex2num(unsigned char *in){
unsigned char *pin = in; // lets use pointer to loop through the string
long out = 0; // here we accumulate the result
while(*pin != 0){
out <<= 4; // we have one more input character, so
// we shift the accumulated interim-result one order up
out += (*pin < 'A') ? *pin & 0xF : (*pin & 0x7) + 9; // add the new nibble
pin++; // go ahead
}
return out;
}
// main function will test our conversion fn
int main(void) {
unsigned char str[] = "1800785"; // no 0x prefix, please
long num;
num = ahex2num(str); // call the function
printf("Input: %s\n",str); // print input string
printf("Output: %x\n",num); // print the converted number back as hexa
printf("Check: %ld = %ld \n",num,0x1800785); // check the numeric values matches
return 0;
}
Try below block of code, its working for me.
char p[] = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);
printf("value x: %x - %d", intVal, intVal);
Output is:
value x: 820 - 2080
So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.
int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
int _result = 0;
DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
for(int i=0;i<size;i+=2)
{
int _multiplierFirstValue = 0, _addonSecondValue = 0;
char _firstChar = _hex[offset + i];
if(_firstChar >= 0x30 && _firstChar <= 0x39)
_multiplierFirstValue = _firstChar - 0x30;
else if(_firstChar >= 0x41 && _firstChar <= 0x46)
_multiplierFirstValue = 10 + (_firstChar - 0x41);
char _secndChar = _hex[offset + i + 1];
if(_secndChar >= 0x30 && _secndChar <= 0x39)
_addonSecondValue = _secndChar - 0x30;
else if(_secndChar >= 0x41 && _secndChar <= 0x46)
_addonSecondValue = 10 + (_secndChar - 0x41);
*(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
}
return _result;
}
Usage:
char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);
1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.
Speedtest (1.000.000 calls):
strtol ~ 0.4400s
hexToInt ~ 0.1100s
This is a function to directly convert hexadecimal containing char array to an integer which needs no extra library:
int hexadecimal2int(char *hdec) {
int finalval = 0;
while (*hdec) {
int onebyte = *hdec++;
if (onebyte >= '0' && onebyte <= '9'){onebyte = onebyte - '0';}
else if (onebyte >= 'a' && onebyte <='f') {onebyte = onebyte - 'a' + 10;}
else if (onebyte >= 'A' && onebyte <='F') {onebyte = onebyte - 'A' + 10;}
finalval = (finalval << 4) | (onebyte & 0xF);
}
finalval = finalval - 524288;
return finalval;
}
I have done a similar thing before and I think this might help you.
The following works for me:
int main(){
int co[8];
char ch[8];
printf("please enter the string:");
scanf("%s", ch);
for (int i=0; i<=7; i++) {
if ((ch[i]>='A') && (ch[i]<='F')) {
co[i] = (unsigned int) ch[i]-'A'+10;
} else if ((ch[i]>='0') && (ch[i]<='9')) {
co[i] = (unsigned int) ch[i]-'0'+0;
}
}
Here, I have only taken a string of 8 characters.
If you want you can add similar logic for 'a' to 'f' to give their equivalent hex values. Though, I haven't done that because I didn't need it.
I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :
unsigned hexdec (const char *hex, const int s_hex);
Before the first conversion intialize the array used for conversion with :
void init_hexdec ();
Here the link on github : https://github.com/kevmuret/libhex/
I like #radhoo solution, very efficient on small systems. One can modify the solution for converting the hex to int32_t (hence, signed value).
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
int32_t hex2int(char *hex) {
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Note the return value is int32_t while val is still uint32_t to not overflow.
The
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
is not protected against malformed string.
Here is a solution building upon "sairam singh"s solution. Where that answer is a one to one solution, this one combines two ASCII nibbles into one byte.
// Assumes input is null terminated string.
//
// IN OUT
// -------------------- --------------------
// Offset Hex ASCII Offset Hex
// 0 0x31 1 0 0x13
// 1 0x33 3
// 2 0x61 A 1 0xA0
// 3 0x30 0
// 4 0x00 NULL 2 NULL
int convert_ascii_hex_to_hex2(char *szBufOut, char *szBufIn) {
int i = 0; // input buffer index
int j = 0; // output buffer index
char a_byte;
// Two hex digits are combined into one byte
while (0 != szBufIn[i]) {
// zero result
szBufOut[j] = 0;
// First hex digit
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -1; // error with first digit
}
szBufOut[j] = a_byte << 4;
// second hex digit
i++;
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -2; // error with second digit
}
szBufOut[j] |= a_byte;
i++;
j++;
}
szBufOut[j] = 0;
return 0; // normal exit
}
I know this is really old but I think the solutions looked too complicated. Try this in VB:
Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer
Dim SumValue as Long
Dim iVal as long
Dim AscVal as long
iLen = Len(sHEX)
For i = 1 to Len(sHEX)
AscVal = Asc(UCase(Mid$(sHEX, i, 1)))
If AscVal >= 48 And AscVal <= 57 Then
iVal = AscVal - 48
ElseIf AscVal >= 65 And AscVal <= 70 Then
iVal = AscVal - 55
End If
SumValue = SumValue + iVal * 16 ^ (iLen- i)
Next i
HexToInt = SumValue
End Function
I'm looking for the least amount of code in C, in order to convert a char to int, where it flags -1 (or any error flag) if the char is not a valid hex digit.
here's what I came up with, is there a shorter way?
// input example
char input = 'f';
// conversion segment
int x = input - '0';
if (!((x >= 49 && x <= 54) || (x >= 0 && x <= 9))) x = -1;
if (x > 9) x -= 39;
// test print
printf("%d", x);
This code assumes ASCII and converts all 256 characters codes into 256 different codes, partially '0'-'9' 'A'-'F' map to 0,1,...15.
For additional tricks and simplification see the post
unsigned char ch = GetData(); // Fetch 1 byte of incoming data;
if (!(--ch & 64)) { // decrement, then if in the '0' to '9' area ...
ch = (ch + 7) & (~64); // move 0-9 next to A-Z codes
}
ch -= 54; // -= 'A' - 10 - 1
if (ch > 15) {
; // handle error
}
Try this function:
isxdigit(c);
I'm create CRC-CCITT Encode (Polynomail 0x1021 and Initial Value is 0xFFFF)
It is correct 8bit, 16bit, 24bit, 32bit ... (1 Byte, 2Byte, 3Byte ...)
But not correct answer 12bit, 20bit, 28bit (not Byte)
I find this algorithm
function crc(bit array bitString[1..len], int polynomial) {
shiftRegister := initial value // 00000000 OR 11111111
for i from 1 to len {
if (shiftRegister top bit) xor bitString[i] = 1
shiftRegister := (shiftRegister left shift 1) xor polynomial
else
shiftRegister := shiftRegister left shift 1
}
return shiftRegister
}
and my source code is like that
// crc_ccitt.h
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
static const char CRC_CCITT[] = "0001000000100001";
static char Shift_Register[] = "1111111111111111";
char* getCRC(char *, int);
void leftShift(char *);
void xorCalc();
char* getCRC(char* dataCode, int dataCodeLength) {
int i;
for (i = 0; i < dataCodeLength; i++) {
if ((Shift_Register[0] == '1' && dataCode[i] == '0')
|| (Shift_Register[0] == '0' && dataCode[i] == '1')) {
leftShift(Shift_Register);
xorCalc();
} else {
leftShift(Shift_Register);
}
printf("%c%c%c%c ", Shift_Register[0], Shift_Register[1], Shift_Register[2], Shift_Register[3]);
printf("%c%c%c%c ", Shift_Register[4], Shift_Register[5], Shift_Register[6], Shift_Register[7]);
printf("%c%c%c%c ", Shift_Register[8], Shift_Register[9], Shift_Register[10], Shift_Register[11]);
printf("%c%c%c%c ", Shift_Register[12], Shift_Register[13], Shift_Register[14], Shift_Register[15]);
printf("\n");
}
return Shift_Register;
}
void leftShift(char *Shift_Register) {
memmove(Shift_Register, Shift_Register + 1, strlen(Shift_Register) - 1);
memset(Shift_Register + strlen(Shift_Register) - 1, '0', 1);
}
void xorCalc() {
int i;
for (i = 0; i < 16; ++i) {
if ((Shift_Register[i] == '1' && CRC_CCITT[i] == '0')
|| (Shift_Register[i] == '0' && CRC_CCITT[i] == '1')) {
Shift_Register[i] = '1';
} else {
Shift_Register[i] = '0';
}
}
}
// crc_ccitt.c
#include "crc_ccitt.h"
int main() {
char dataCode[256];
char *CRC = "";
printf("Input Data Code: ");
gets(dataCode);
/*
puts(dataCode);
rightShift(dataCode);
puts(dataCode);
*/
CRC = getCRC(dataCode, strlen(dataCode));
//printf("%s", CRC);
return 0;
}
I confirm CRC Encode value with this page
http://www.lammertbies.nl/comm/info/crc-calculation.html
For example
Input 0001111111110010(1FF2)
page : C11F
my program : 1100 0001 0001 1111 (C11F)
But
Input 000111111111 (1FF)
page : FFAD
my program : 1101 0011 0000 1111 (D30F)
What of lack of my program??
Or, is algorithm is wrong??
Program OK
Algorithm OK
User input is likely the error.
Your CRC "0001000000100001" is for a 16-bit operation.
Your failed input is "000111111111", 12 bits.
Instead try using "0000000111111111" or "0001111111110000" (pad on the left or right)
Note: I would have tried it myself but you did not provide crc_ccitt.h
I have a char[] that contains a value such as "0x1800785" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched around but cannot find an answer. Thanks.
Have you tried strtol()?
strtol - convert string to a long integer
Example:
const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);
In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:
const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);
(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)
Or if you want to have your own implementation, I wrote this quick function as an example:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Something like this could be useful:
char str[] = "0x1800785";
int num;
sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num);
Read man sscanf
Assuming you mean it's a string, how about strtol?
Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.
#include <inttypes.h>
/**
* xtou64
* Take a hex string and convert it to a 64bit number (max 16 hex digits).
* The string must only contain digits and valid hex characters.
*/
uint64_t xtou64(const char *str)
{
uint64_t res = 0;
char c;
while ((c = *str++)) {
char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
res = (res << 4) | (uint64_t) v;
}
return res;
}
The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.
One quick & dirty solution:
// makes a number from two ascii hexa characters
int ahex2int(char a, char b){
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
return (a << 4) + b;
}
You have to be sure your input is correct, no validation included (one could say it is C). Good thing it is quite compact, it works with both 'A' to 'F' and 'a' to 'f'.
The approach relies on the position of alphabet characters in the ASCII table, let's peek e.g. to Wikipedia (https://en.wikipedia.org/wiki/ASCII#/media/File:USASCII_code_chart.png). Long story short, the numbers are below the characters, so the numeric characters (0 to 9) are easily converted by subtracting the code for zero. The alphabetic characters (A to F) are read by zeroing other than last three bits (effectively making it work with either upper- or lowercase), subtracting one (because after the bit masking, the alphabet starts on position one) and adding ten (because A to F represent 10th to 15th value in hexadecimal code). Finally, we need to combine the two digits that form the lower and upper nibble of the encoded number.
Here we go with same approach (with minor variations):
#include <stdio.h>
// takes a null-terminated string of hexa characters and tries to
// convert it to numbers
long ahex2num(unsigned char *in){
unsigned char *pin = in; // lets use pointer to loop through the string
long out = 0; // here we accumulate the result
while(*pin != 0){
out <<= 4; // we have one more input character, so
// we shift the accumulated interim-result one order up
out += (*pin < 'A') ? *pin & 0xF : (*pin & 0x7) + 9; // add the new nibble
pin++; // go ahead
}
return out;
}
// main function will test our conversion fn
int main(void) {
unsigned char str[] = "1800785"; // no 0x prefix, please
long num;
num = ahex2num(str); // call the function
printf("Input: %s\n",str); // print input string
printf("Output: %x\n",num); // print the converted number back as hexa
printf("Check: %ld = %ld \n",num,0x1800785); // check the numeric values matches
return 0;
}
Try below block of code, its working for me.
char p[] = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);
printf("value x: %x - %d", intVal, intVal);
Output is:
value x: 820 - 2080
So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.
int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
int _result = 0;
DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
for(int i=0;i<size;i+=2)
{
int _multiplierFirstValue = 0, _addonSecondValue = 0;
char _firstChar = _hex[offset + i];
if(_firstChar >= 0x30 && _firstChar <= 0x39)
_multiplierFirstValue = _firstChar - 0x30;
else if(_firstChar >= 0x41 && _firstChar <= 0x46)
_multiplierFirstValue = 10 + (_firstChar - 0x41);
char _secndChar = _hex[offset + i + 1];
if(_secndChar >= 0x30 && _secndChar <= 0x39)
_addonSecondValue = _secndChar - 0x30;
else if(_secndChar >= 0x41 && _secndChar <= 0x46)
_addonSecondValue = 10 + (_secndChar - 0x41);
*(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
}
return _result;
}
Usage:
char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);
1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.
Speedtest (1.000.000 calls):
strtol ~ 0.4400s
hexToInt ~ 0.1100s
This is a function to directly convert hexadecimal containing char array to an integer which needs no extra library:
int hexadecimal2int(char *hdec) {
int finalval = 0;
while (*hdec) {
int onebyte = *hdec++;
if (onebyte >= '0' && onebyte <= '9'){onebyte = onebyte - '0';}
else if (onebyte >= 'a' && onebyte <='f') {onebyte = onebyte - 'a' + 10;}
else if (onebyte >= 'A' && onebyte <='F') {onebyte = onebyte - 'A' + 10;}
finalval = (finalval << 4) | (onebyte & 0xF);
}
finalval = finalval - 524288;
return finalval;
}
I have done a similar thing before and I think this might help you.
The following works for me:
int main(){
int co[8];
char ch[8];
printf("please enter the string:");
scanf("%s", ch);
for (int i=0; i<=7; i++) {
if ((ch[i]>='A') && (ch[i]<='F')) {
co[i] = (unsigned int) ch[i]-'A'+10;
} else if ((ch[i]>='0') && (ch[i]<='9')) {
co[i] = (unsigned int) ch[i]-'0'+0;
}
}
Here, I have only taken a string of 8 characters.
If you want you can add similar logic for 'a' to 'f' to give their equivalent hex values. Though, I haven't done that because I didn't need it.
I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :
unsigned hexdec (const char *hex, const int s_hex);
Before the first conversion intialize the array used for conversion with :
void init_hexdec ();
Here the link on github : https://github.com/kevmuret/libhex/
I like #radhoo solution, very efficient on small systems. One can modify the solution for converting the hex to int32_t (hence, signed value).
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
int32_t hex2int(char *hex) {
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Note the return value is int32_t while val is still uint32_t to not overflow.
The
uint32_t val = *hex > 56 ? 0xFFFFFFFF : 0;
is not protected against malformed string.
Here is a solution building upon "sairam singh"s solution. Where that answer is a one to one solution, this one combines two ASCII nibbles into one byte.
// Assumes input is null terminated string.
//
// IN OUT
// -------------------- --------------------
// Offset Hex ASCII Offset Hex
// 0 0x31 1 0 0x13
// 1 0x33 3
// 2 0x61 A 1 0xA0
// 3 0x30 0
// 4 0x00 NULL 2 NULL
int convert_ascii_hex_to_hex2(char *szBufOut, char *szBufIn) {
int i = 0; // input buffer index
int j = 0; // output buffer index
char a_byte;
// Two hex digits are combined into one byte
while (0 != szBufIn[i]) {
// zero result
szBufOut[j] = 0;
// First hex digit
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -1; // error with first digit
}
szBufOut[j] = a_byte << 4;
// second hex digit
i++;
if ((szBufIn[i]>='A') && (szBufIn[i]<='F')) {
a_byte = (unsigned int) szBufIn[i]-'A'+10;
} else if ((szBufIn[i]>='a') && (szBufIn[i]<='f')) {
a_byte = (unsigned int) szBufIn[i]-'a'+10;
} else if ((szBufIn[i]>='0') && (szBufIn[i]<='9')) {
a_byte = (unsigned int) szBufIn[i]-'0';
} else {
return -2; // error with second digit
}
szBufOut[j] |= a_byte;
i++;
j++;
}
szBufOut[j] = 0;
return 0; // normal exit
}
I know this is really old but I think the solutions looked too complicated. Try this in VB:
Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer
Dim SumValue as Long
Dim iVal as long
Dim AscVal as long
iLen = Len(sHEX)
For i = 1 to Len(sHEX)
AscVal = Asc(UCase(Mid$(sHEX, i, 1)))
If AscVal >= 48 And AscVal <= 57 Then
iVal = AscVal - 48
ElseIf AscVal >= 65 And AscVal <= 70 Then
iVal = AscVal - 55
End If
SumValue = SumValue + iVal * 16 ^ (iLen- i)
Next i
HexToInt = SumValue
End Function
I want to convert two ASCII bytes to one hexadecimal byte.
eg.
0x30 0x43 => 0x0C , 0x34 0x46 => 0x4F ...
The ASCII bytes are a number between 0 and 9 or a letter between A and F (upper case only), so between 0x30 ... 0x39 and 0x41 ... 0x46
I know how "to construct" 0x4F with the numbers 0x34 and 0x46 : 0x4F = 0x34 * 0x10 + 0x46
So, in fact, i would to convert one ASCII byte in hexadecimal value.
For that, i can build and array to assign the hexadecimal value to the ASCII char :
0x30 => 0x00
0x31 => 0x01
...
0x46 => 0x0F
But, maybe it have a most « proper » solution.
The program will be run on an AVR µC and is compiled with avr-gcc, so scanf() / printf() solutions aren't suitable.
Have you got an idea ?
Thanks
i can't make sense of your examples, but if you want to convert a string containing hexadecimal ascii characters to its byte value (e.g. so the string "56" becomes the byte 0x56, you can use this (which assumes your system is using ASCII)
uint8_t*
hex_decode(const char *in, size_t len,uint8_t *out)
{
unsigned int i, t, hn, ln;
for (t = 0,i = 0; i < len; i+=2,++t) {
hn = in[i] > '9' ? in[i] - 'A' + 10 : in[i] - '0';
ln = in[i+1] > '9' ? in[i+1] - 'A' + 10 : in[i+1] - '0';
out[t] = (hn << 4 ) | ln;
}
return out;
}
You'd use it like e.g.
char x[]="1234";
uint8_t res[2];
hex_decode(x,strlen(x),res);
And res (which must be at least half the length of the in parameter) now contains the 2 bytes 0x12,0x34
Note also that this code needs the hexadecimal letters A-F to be capital, a-f won't do (and it doesn't do any error checking - so you'll have to pass it valid stuff).
You can use strtol(), which is part of avr-libc, or you can write just your specific case pretty easily:
unsigned char charToHexDigit(char c)
{
if (c >= 'A')
return c - 'A' + 10;
else
return c - '0';
}
unsigned char stringToByte(char c[2])
{
return charToHexDigit(c[0]) * 16 + charToHexDigit(c[1]);
}
The task:
Convert a string containing hexadecimal ascii characters to its byte values
so ascii "FF" becomes 0xFF and ascii "10" (x31x30x00) becomes 0x10
char asciiString[]="aaAA12fF";// input ascii hex string
char result[4]; // byte equivalent of the asciiString (the size should be at half of asciiString[])
// the final result should be:
result[0] = 0xAA;
result[1] = 0xAA;
result[2] = 0x12;
result[3] = 0xFF;
//1. Firt step: convert asciiString so it contains upper cases only:
// convert string to upper cases:
stringToUpperCases(asciiString);
use:
void stringToUpperCases(char *p)
{
for(int i=0; *(p+i) !='\0'; i++)
{
*(p+i) = (unsigned char) toupper( *(p+i) );
}
}
//2. Convert a string containing hexadecimal ascii characters to its byte values:
// convert string to bytes:
int nrOfBytes = stringToBytes(asciiString,result);
//use:
unsigned char charToHexDigit(char c)
{
if (c >= 'A')
return (c - 'A' + 10);
else
return (c - '0');
}
unsigned char ascii2HexToByte(char *ptr)
{
return charToHexDigit( *ptr )*16 + charToHexDigit( *(ptr+1) );
}
int stringToBytes(char *string, char *result)
{
int k=0;
int strLen = strlen(string);
for(int i = 0; i < strLen; i = i + 2)
{
result[k] = ascii2HexToByte( &string[i] );
k++;
}
return k; // number of bytes in the result array
}
//3. print result:
printNrOfBytes(nrOfBytes, result);
// use:
void printNrOfBytes(int nr, char *p)
{
for(int i= 0; i < nr; i++)
{
printf( "0x%02X ", (unsigned char)*(p+i) );
}
printf( "\n");
}
//4. The result should be:
0xAA 0xAA 0x12 0xFF
//5. This is the test program:
char asciiString[]="aaAA12fF"; // input ascii hex string
char result[4]; // result
// convert string to upper cases:
stringToUpperCases(asciiString);
// convert string to bytes
int nrOfBytes = stringToBytes(asciiString,result);
// print result:
printNrOfBytes(nrOfBytes, result);
// result:
// 0xAA 0xAA 0x12 0xFF
It's works, but could be much optimized !
inline uint8_t twoAsciiByteToByte(const std::string& s)
{
uint8_t r = 0;
if (s.length() == 4)
{
uint8_t a = asciiToByte(s[0]);
uint8_t b = asciiToByte(s[1]);
uint8_t c = asciiToByte(s[2]);
uint8_t d = asciiToByte(s[3]);
int h = (a * 10 + b);
int l = (c * 10 + d);
if (s[0] == '3')
h -= 30;
else if (s[0] == '4')
h -= 31;
if (s[2] == '3')
l -= 30;
else if (s[2] == '4')
l -= 31;
r = (h << 4) | l;
}
return r;
}
Here's a version that works with both upper and lower-case hex strings:
void hex_decode(const char *in, size_t len, uint8_t *out)
{
unsigned int i, hn, ln;
char hc, lc;
memset(out, 0, len);
for (i = 0; i < 2*len; i += 2) {
hc = in[i];
if ('a' <= hc && hc <= 'f') hc = toupper(hc);
lc = in[i+1];
if ('a' <= lc && lc <= 'f') lc = toupper(lc);
hn = hc > '9' ? hc - 'A' + 10 : hc - '0';
ln = lc > '9' ? lc - 'A' + 10 : lc - '0';
out[i >> 1] = (hn << 4 ) | ln;
}
}
Converting 2 hex chars to a byte is done in two steps:
Convert char a and b to their number (e.g. 'F' -> 0xF), which is done in two big if else branches, that check if the char is in the range '0' to '9', 'A' to 'F' or 'a' to 'f'.
In the 2nd step the two numbers are joined by shifting a (largest value is 0xF (0b0000_FFFF)) 4 to the left (a << 4 -> 0b1111_0000) and then apply the bitwise or operation on a and b ((a << 4) | b):
a: 0000_1111
b: 1111_0000
-> 1111_1111
#include <stdio.h>
#include <stdint.h>
#define u8 uint8_t
#define u32 uint32_t
u8 to_hex_digit(char a, char b) {
u8 result = 0;
if (a >= 0x30 && a <= 0x39) {
result = (a - 0x30) << 4;
} else if (a >= 0x41 && a <= 0x46) {
result = (a - 0x41 + 10) << 4;
} else if (a >= 0x61 && a <= 0x7A) {
result = (a - 0x61 + 10) << 4;
} else {
printf("invalid hex digit: '%c'\n", a);
}
if (b >= 0x30 && b <= 0x39) {
result |= b - 0x30;
} else if (b >= 0x41 && b <= 0x46) {
result |= b - 0x41 + 10;
} else if (b >= 0x61 && b <= 0x7A) {
result |= b - 0x61 + 10;
} else {
printf("invalid hex digit: '%c'\n", b);
}
return result;
}
u32 main() {
u8 result = to_hex_digit('F', 'F');
printf("0x%X (%d)\n", result, result);
return 0;
}