How to convert a float to a 4 byte char in C? - c

I want to convert a float number for example 2.45 to the 4 byte char array.
so the 2.45 should look like this '#' 'FS' 'Ì' 'Í' which is binary the ieee representation of 2.45 = 01000000 00011100 11001100 11001101?
I've solved the problem but it has a bad complexity. do you have any good ideas?
Thanks for the good answers.
can you please tell me the way back from the char array to the float number ?

Just use memcpy:
#include <string.h>
float f = 2.45f;
char a[sizeof(float)];
memcpy(a, &f, sizeof(float));
If you require the opposite endianness then it is a trivial matter to reverse the bytes in a afterwards, e.g.
int i, j;
for (i = 0, j = sizeof(float) - 1; i < j; ++i, --j)
{
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}

You have a few ways of doing this, including these two:
Use typecasting and pointers:
float f = 2.45;
char *s = (char *) &f;
Note that this isn't safe in any way and that there is no string terminator after the "string".
Use a union:
union u
{
float f;
char s[sizeof float];
};
union u foo;
foo.f = 2.45;
The char array can now be accessed to get the byte values. Also note like the first alternative there is no string terminator.

one can convert a float to a char using typecasting and pointers as follows:
float t= -2.63646464;
char *float2CharArr;
float2CharArr = (char*) &t;
Mind you above there's no \0 string terminator. To append it one can do it, for instance, like so:
char* tmp = realloc(float2CharArr, sizeof(*float2CharArr)+1);
tmp[sizeof(*float2CharArr)+1] = '\0';
float2CharArr=tmp;
Another, more elaborate way to convert a float value into a char string can be achieved using the following code below:
union int32_Float_t
{
int32_t Long;
float Float;
};
#ifndef HUGE_VALF
#define HUGE_VALF (__builtin_huge_valf())
#endif
#ifndef FLT_MIN_EXP
#define FLT_MIN_EXP (-999)
#endif
#ifndef FLT_MAX_EXP
#define FLT_MAX_EXP (999)
#endif
#define _FTOA_TOO_LARGE -2 // |input| > 2147483520
#define _FTOA_TOO_SMALL -1 // |input| < 0.0000001
//precision 0-9
#define PRECISION 7
//_ftoa function
void _ftoa(float f, char *p, int *status)
{
int32_t mantissa, int_part, frac_part;
int16_t exp2;
int32_Float_t x;
*status = 0;
if (f == 0.0)
{
*p++ = '0';
*p++ = '.';
*p++ = '0';
*p = 0;
return;
}
x.Float = f;
exp2 = (unsigned char)(x.Long>>23) - 127;
mantissa = (x.Long&0xFFFFFF) | 0x800000;
frac_part = 0;
int_part = 0;
if (exp2 >= 31)
{
*status = _FTOA_TOO_LARGE;
return;
}
else if (exp2 < -23)
{
*status = _FTOA_TOO_SMALL;
return;
}
else if (exp2 >= 23)
{
int_part = mantissa<<(exp2 - 23);
}
else if (exp2 >= 0)
{
int_part = mantissa>>(23 - exp2);
frac_part = (mantissa<<(exp2 + 1))&0xFFFFFF;
}
else
{
//if (exp2 < 0)
frac_part = (mantissa&0xFFFFFF)>>-(exp2 + 1);
}
if (x.Long < 0)
*p++ = '-';
if (int_part == 0)
*p++ = '0';
else
{
ltoa(int_part, p, 10);
while (*p)
p++;
}
*p++ = '.';
if (frac_part == 0)
*p++ = '0';
else
{
char m;
for (m=0; m<PRECISION; m++)
{
//frac_part *= 10;
frac_part = (frac_part<<3) + (frac_part<<1);
*p++ = (frac_part>>24) + '0';
frac_part &= 0xFFFFFF;
}
//delete ending zeroes
for (--p; p[0] == '0' && p[-1] != '.'; --p)
;
++p;
}
*p = 0;
}
Below is an example on how to using on Arduino Studio and related coding platforms for MCU programming:
void setup(void)
{
int i, stat;
char s[20];
float f[] = { 0.0, -0.0, 42.0, 123.456789, 0.0000018, 555555.555,
-888888888.8888888, 11111111.2 };
Serial.begin(9600);
for ( i=0; i<8; i++ )
{
if ( _ftoa(f[i], s, &stat) == 0 )
{
Serial.print( "_ftoa: " );
Serial.println( s );
}
}
}
void loop(void) { }
This source code is posted around the internet in various places, mostly without attribution. For instance here and here. So credit to the anonymous author.

Related

Convert a float number to char array on C

I am trying to convert a float number to a char array.
sprintf() will not work for me and neither will dtostrf.
Since I have a limit in the decimal number (it is 5) I tried this:
int num = f;
int decimales = (f-num)*10000;
Everything worked fine until I typed the number 123.050. Instead of giving me the decimal part as "0.50" it gives me a 5000, because it does not count the 0 now that my "decimal" variable is an int.
Is there any other way to convert it?
You want a quick and dirty way to produce a string with the decimal representation of your float without linking sprintf because of space constraints on an embedded system. The number of decimals is fixed. Here is a proposal:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ftoa(char *dest, size_t size, double val, int dec) {
char *p = dest;
char *q = dest + size;
long long mul = 1;
long long num;
int i;
if (size == 0)
return NULL;
*--q = '\0';
if (size == 1)
goto fail;
if (val < 0) {
val = -val;
if (p >= q)
goto fail;
*p++ = '-';
}
for (i = 0; i < dec; i++) {
mul *= 10;
}
num = (long long)(val * mul + 0.5);
for (i = 1; i < dec + 2 || num > 0; i++) {
if (p >= q)
goto fail;
*--q = '0' + (num % 10);
num = num / 10;
if (i == dec) {
if (p >= q)
goto fail;
*--q = '.';
}
}
memmove(p, q, dest + size - q);
return dest;
fail:
return memset(dest, '*', size - 1);
}
int main(int argc, char *argv[]) {
char buf[24];
for (int i = 1; i < argc; i++) {
double d = strtod(argv[i], NULL);
int dec = 5;
if (i + 1 < argc)
dec = atoi(argv[++i]);
printf("%s\n", ftoa(buf, sizeof buf, d, dec));
}
return 0;
}
Use %04d in printf()
const int D4 = 10000;
double f = 123.050;
int i = round(f*D4);
int num = i / D4;
int decimales = i % D4;
printf("%d.%04d\n", num, decimales);
gives
123.0500
If you worry about an int overflow (since we multiply the number by 10000), use long, or long long instead...
To save decimals in a string including the leading zero(es)
char sdec[5];
sprintf(sdec, "%04d", decimales);
sdec contains the decimals, including the leading zero.
(see also Is floating point math broken? )

Add or subtract two numbers represented as Strings without using int, double, long, float, etc

My assignment for this question has already passed and I guess I misunderstood the question altogether by using numerical data types in some parts of my code. So I'm just curious as to how to solve this problem of adding/subtracting subtract two numbers represented as Strings without using numerical data types. By numerical data types, I just mean int, double, long, etc and everything needs to stay in String form.
Here is a function that performs addition of numbers in string format into an array of char, assumed to be sufficiently large and different from a and b:
char *add_numbers(char *dest, const char *a, const char *b) {
size_t lena = strlen(a);
size_t lenb = strlen(b);
size_t len = lena > lenb ? lena + 1 : lenb + 1;
char carry = 0;
dest[len] = '\0';
while (lena > 0 && lenb > 0) {
char digit = a[--lena] - '0' + b[--lenb] + carry;
carry = 0;
if (digit > '9') {
carry = 1;
digit -= 10;
}
dest[--len] = digit;
}
if (lenb > 0) {
lena = lenb;
a = b;
}
while (lena > 0) {
char digit = a[--lena] + carry;
carry = 0;
if (digit > '9') {
carry = 1;
digit -= 10;
}
dest[--len] = digit;
}
if (carry) {
dest[--len] = '1';
} else {
for (;; len++) {
dest[len - 1] = dest[len];
if (dest[len] == '\0')
break;
}
}
return dest;
}
No int, double, long, float. The number is not converted into numerical format, the operation is performed one digit at a time, in string format.
I'm guessing that you need to do arithmetic on strings digit by digit.
Like many assignments you will get in school, there is really no point in being able to do arithmetic this way, you are just supposed to learn something about the different operations and thought patterns you would need to go through.
For addition, lets take the example add("9","12") // returns "21"
In order to write this function, we will do addition the same way you learned to do it in school, first the one's digit, then the ten's and so on.
to do this, we will break call an add_digit function once for every digit.
This function will need to take the corresponding digit from both a and b as well as any carry that resulted from the addition of the previous digits.
The following code is a complete example of doing this.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
const char * shortest(const char * a, const char * b){
if (strlen(a) <= strlen(b)){
return a;
}
return b;
}
const char * longest(const char * a, const char * b){
if (strlen(a) <= strlen(b)){
return b;
}
return a;
}
const char * add_digit(char a, char b, char carry){
/*printf("a : %c, b : %c, carry : %c\n", a, b, carry);*/
static char out[2] = {'0','0'};
int a_int = (int)(a - 48);
int b_int = (int)(b - 48);
int carry_int = (int)(carry - 48);
int sum = a_int + b_int + carry_int;
if (sum > 9){
out[0] = (sum / 10) + 48;
sum %= 10;
}
out [1] = sum + 48;
return out;
}
const char * add(const char * a, const char * b){
const char * s = shortest(a,b);
const char * l = longest(a,b);
unsigned i;
char carry = '0';
char * out = malloc(strlen(l) + 1);
for (i = strlen(l); i--;){
out[i] = ' ';
}
out[strlen(l)] = '\0';
for (i = 0; i < strlen(l); i++){
const char * digit;
if (i < strlen(s)){
digit = add_digit(s[strlen(s) - i - 1], l[strlen(l) - i - 1], carry);
} else {
digit = add_digit('0', l[strlen(l) - i - 1], carry);
}
carry = digit[0];
out[strlen(l) - i] = digit[1];
}
out[0] = carry;
return out;
}
int main(){
printf("9999 + 9 = %s\n", add("9999", "9"));
}

C Code for Hexadecimal without using standard libraries

I want to write C Code which converts first string into integer then integer into hexadecimal.
ex: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,240 and convert into long/integer value
any help is appreciated.
#include <stdio.h> // testing
int main(int argc, char** argv) // testing
{
char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing
char* ip = ipString;
unsigned int hex;
for( int i = 0; i < 4; i++ ){
unsigned int n = 0;
for( char c; (c = *ip) >= '0' && c <= '9'; ip++ )
n = 10 * n + c - '0';
hex = (hex << 8) + n;
if( *ip == '.' ) ip++;
}
printf("%08X\n", hex); // testing
return 0; // testing
}
Maybe something like this?
char sn[4];
char *nid = hexString;
int nip[4];
int xnip[4];
int j = 0;
while (*nid != '\0') {
int i = 0;
memset(sn, '\0', sizeof sn);
while (isdigit(*nid)) {
sn[i++] = *nid++;
}
if (*nid == '.')
nid++;
// now sn should be the number part
nip[j] = your_str_to_int(sn);
xnip[j] = your_int_to_hex(nip[j]);
j++;
}
int main(void)
{
char hexChars[] = "0123456789ABCDEF";
char ipString[] = "172.24.18.254";
char hexString[9] = "";
const char* pch = ipString;
int num = 0;
int i = 0;
do
{
if (*pch != '.' && *pch != '\0')
{
num *= 10;
num += (*pch - '0');
}
else
{
hexString[i++] = hexChars[num / 16];
hexString[i++] = hexChars[num % 16];
num = 0;
}
} while (*pch++);
return 0;
}
The hex values will stored in hexString.
int i = 0, sum = 0;
char ipString[] = "172.24.18.240";
do
{
if (isdigit(ipString[i])) sum = sum * 10 + ipString[i] - '0';
else
{ putchar("0123456789ABCDEF"[sum / 16]);
putchar("0123456789ABCDEF"[sum % 16]);
putchar('.');
sum = 0;
}
}
while (ipString[i++] != '\0');
More or less ugly, but should work on IP addresses.

Convert integer to string without access to libraries

I recently read a sample job interview question:
Write a function to convert an integer
to a string. Assume you do not have
access to library functions i.e.,
itoa(), etc...
How would you go about this?
fast stab at it: (edited to handle negative numbers)
int n = INT_MIN;
char buffer[50];
int i = 0;
bool isNeg = n<0;
unsigned int n1 = isNeg ? -n : n;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf(buffer);
A look on the web for itoa implementation will give you good examples. Here is one, avoiding to reverse the string at the end. It relies on a static buffer, so take care if you reuse it for different values.
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
The algorithm is easy to see in English.
Given an integer, e.g. 123
divide by 10 => 123/10. Yielding, result = 12 and remainder = 3
add 30h to 3 and push on stack (adding 30h will convert 3 to ASCII representation)
repeat step 1 until result < 10
add 30h to result and store on stack
the stack contains the number in order of | 1 | 2 | 3 | ...
I would keep in mind that all of the digit characters are in increasing order within the ASCII character set and do not have other characters between them.
I would also use the / and the% operators repeatedly.
How I would go about getting the memory for the string would depend on information you have not given.
Assuming it is in decimal, then like this:
int num = ...;
char res[MaxDigitCount];
int len = 0;
for(; num > 0; ++len)
{
res[len] = num%10+'0';
num/=10;
}
res[len] = 0; //null-terminating
//now we need to reverse res
for(int i = 0; i < len/2; ++i)
{
char c = res[i]; res[i] = res[len-i-1]; res[len-i-1] = c;
}
An implementation of itoa() function seems like an easy task but actually you have to take care of many aspects that are related on your exact needs. I guess that in the interview you are expected to give some details about your way to the solution rather than copying a solution that can be found in Google (http://en.wikipedia.org/wiki/Itoa)
Here are some questions you may want to ask yourself or the interviewer:
Where should the string be located (malloced? passed by the user? static variable?)
Should I support signed numbers?
Should i support floating point?
Should I support other bases rather then 10?
Do we need any input checking?
Is the output string limited in legth?
And so on.
Convert integer to string without access to libraries
Convert the least significant digit to a character first and then proceed to more significant digits.
Normally I'd shift the resulting string into place, yet recursion allows skipping that step with some tight code.
Using neg_a in myitoa_helper() avoids undefined behavior with INT_MIN.
// Return character one past end of character digits.
static char *myitoa_helper(char *dest, int neg_a) {
if (neg_a <= -10) {
dest = myitoa_helper(dest, neg_a / 10);
}
*dest = (char) ('0' - neg_a % 10);
return dest + 1;
}
char *myitoa(char *dest, int a) {
if (a >= 0) {
*myitoa_helper(dest, -a) = '\0';
} else {
*dest = '-';
*myitoa_helper(dest + 1, a) = '\0';
}
return dest;
}
void myitoa_test(int a) {
char s[100];
memset(s, 'x', sizeof s);
printf("%11d <%s>\n", a, myitoa(s, a));
}
Test code & output
#include "limits.h"
#include "stdio.h"
int main(void) {
const int a[] = {INT_MIN, INT_MIN + 1, -42, -1, 0, 1, 2, 9, 10, 99, 100,
INT_MAX - 1, INT_MAX};
for (unsigned i = 0; i < sizeof a / sizeof a[0]; i++) {
myitoa_test(a[i]);
}
return 0;
}
-2147483648 <-2147483648>
-2147483647 <-2147483647>
-42 <-42>
-1 <-1>
0 <0>
1 <1>
2 <2>
9 <9>
10 <10>
99 <99>
100 <100>
2147483646 <2147483646>
2147483647 <2147483647>
The faster the better?
unsigned countDigits(long long x)
{
int i = 1;
while ((x /= 10) && ++i);
return i;
}
unsigned getNumDigits(long long x)
{
x < 0 ? x = -x : 0;
return
x < 10 ? 1 :
x < 100 ? 2 :
x < 1000 ? 3 :
x < 10000 ? 4 :
x < 100000 ? 5 :
x < 1000000 ? 6 :
x < 10000000 ? 7 :
x < 100000000 ? 8 :
x < 1000000000 ? 9 :
x < 10000000000 ? 10 : countDigits(x);
}
#define tochar(x) '0' + x
void tostr(char* dest, long long x)
{
unsigned i = getNumDigits(x);
char negative = x < 0;
if (negative && (*dest = '-') & (x = -x) & i++);
*(dest + i) = 0;
while ((i > negative) && (*(dest + (--i)) = tochar(((x) % 10))) | (x /= 10));
}
If you want to debug, You can split the conditions (instructions) into
lines of code inside the while scopes {}.
I came across this question so I decided to drop by the code I usually use for this:
char *SignedIntToStr(char *Dest, signed int Number, register unsigned char Base) {
if (Base < 2 || Base > 36) {
return (char *)0;
}
register unsigned char Digits = 1;
register unsigned int CurrentPlaceValue = 1;
for (register unsigned int T = Number/Base; T; T /= Base) {
CurrentPlaceValue *= Base;
Digits++;
}
if (!Dest) {
Dest = malloc(Digits+(Number < 0)+1);
}
char *const RDest = Dest;
if (Number < 0) {
Number = -Number;
*Dest = '-';
Dest++;
}
for (register unsigned char i = 0; i < Digits; i++) {
register unsigned char Digit = (Number/CurrentPlaceValue);
Dest[i] = (Digit < 10? '0' : 87)+Digit;
Number %= CurrentPlaceValue;
CurrentPlaceValue /= Base;
}
Dest[Digits] = '\0';
return RDest;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
char String[32];
puts(SignedIntToStr(String, -100, 16));
return 0;
}
This will automatically allocate memory if NULL is passed into Dest. Otherwise it will write to Dest.
Here's a simple approach, but I suspect if you turn this in as-is without understanding and paraphrasing it, your teacher will know you just copied off the net:
char *pru(unsigned x, char *eob)
{
do { *--eob = x%10; } while (x/=10);
return eob;
}
char *pri(int x, char *eob)
{
eob = fmtu(x<0?-x:x, eob);
if (x<0) *--eob='-';
return eob;
}
Various improvements are possible, especially if you want to efficiently support larger-than-word integer sizes up to intmax_t. I'll leave it to you to figure out the way these functions are intended to be called.
Slightly longer than the solution:
static char*
itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
Reverse:
int strlen(const char* str)
{
int i = 0;
while (str != '\0')
{
i++;
str++;
}
return i;
}
static void
reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
And although the decision davolno long here are some useful features for beginners. I hope you will be helpful.
This is the shortest function I can think of that:
Correctly handles all signed 32-bit integers including 0, MIN_INT32, MAX_INT32.
Returns a value that can be printed immediatelly, e.g.: printf("%s\n", GetDigits(-123))
Please comment for improvements:
static const char LARGEST_NEGATIVE[] = "-2147483648";
static char* GetDigits(int32_t x) {
char* buffer = (char*) calloc(sizeof(LARGEST_NEGATIVE), 1);
int negative = x < 0;
if (negative) {
if (x + (1 << 31) == 0) { // if x is the largest negative number
memcpy(buffer, LARGEST_NEGATIVE, sizeof(LARGEST_NEGATIVE));
return buffer;
}
x *= -1;
}
// storing digits in reversed order
int length = 0;
do {
buffer[length++] = x % 10 + '0';
x /= 10;
} while (x > 0);
if (negative) {
buffer[length++] = '-'; // appending minus
}
// reversing digits
for (int i = 0; i < length / 2; i++) {
char temp = buffer[i];
buffer[i] = buffer[length-1 - i];
buffer[length-1 - i] = temp;
}
return buffer;
}
//Fixed the answer from [10]
#include <iostream>
void CovertIntToString(unsigned int n1)
{
unsigned int n = INT_MIN;
char buffer[50];
int i = 0;
n = n1;
bool isNeg = n<0;
n1 = isNeg ? -n1 : n1;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
// Now we must reverse the string
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf("%s", buffer);
}
int main() {
unsigned int x = 4156;
CovertIntToString(x);
return 0;
}
This function converts each digits of number into a char and chars add together
in one stack forming a string. Finally, string is formed from integer.
string convertToString(int num){
string str="";
for(; num>0;){
str+=(num%10+'0');
num/=10;
}
return str;
}

Tiny snippet for converting 4 hex characters to an integer in C

I need to parse strings of four hex characters to an integer. The characters appear inside a longer string, and there are no separators - I just know the offset they can be found in. The hex characters are case insensitive. Example with offset 3:
"foo10a4bar" -> 4260
I'm looking for a snippet that is
Short (too much code always creates complexity)
Simple (simple to understand and verify that it is correct)
Safe (invalid input is detected and signalled, no potential memory problems)
I'm a bit leery of using the 'sscanf' family of functions for this, but if there's a safe ANSI C solution using them, they can be used.
strtol is simple with good error handling:
const int OFFSET = 3, LEN = 4;
char hex[LEN + 1];
int i;
for(i = 0; i < LEN && str[OFFSET + i]; i++)
{
hex[i] = str[OFFSET + i];
if(!isxdigit((unsigned char) hex[i]))
{
// signal error, return
}
}
if(i != LEN)
{
// signal error, return
}
hex[LEN] = '\0';
char *end;
int result = (int) strtol(hex, &end, 16);
if(end != hex + LEN)
{
// signal error, return
}
It's usually best to use standard functions where you can, to get concise and simple code:
#define HEXLEN 4
long extract_hex(const char *src, size_t offset)
{
char hex[HEXLEN + 1] = { 0 };
long val;
if (strlen(src) < offset + HEXLEN)
return -1;
memcpy(hex, src + offset, HEXLEN);
if (strspn(hex, "0123456789AaBbCcDdEeFf") < HEXLEN)
return -1;
errno = 0;
val = strtol(hex, NULL, 16);
/* Out of range - can't occur unless HEXLEN > 7 */
if (errno)
return -1;
return val;
}
Here's my attempt
#include <assert.h>
static int h2d(char c) {
int x;
switch (c) {
default: x = -1; break; /* invalid hex digit */
case '0': x = 0; break;
case '1': x = 1; break;
case '2': x = 2; break;
/* ... */
case 'E': case 'e': x = 14; break;
case 'F': case 'f': x = 15; break;
}
return x;
}
int hex4(const char *src, int offset) {
int tmp, val = 0;
tmp = h2d(*(src+offset+0)); assert(tmp >= 0); val += tmp << 12;
tmp = h2d(*(src+offset+1)); assert(tmp >= 0); val += tmp << 8;
tmp = h2d(*(src+offset+2)); assert(tmp >= 0); val += tmp << 4;
tmp = h2d(*(src+offset+3)); assert(tmp >= 0); val += tmp;
return val;
}
Of course, instead of assert use your preferred method of validation!
And you can use it like this
int val = hex4("foo10a4bar", 3);
Here's an alternative based on character arithmetic:
int hexdigits(char *str, int ndigits)
{
int i;
int n = 0;
for (i=0; i<ndigits; ++i) {
int d = *str++ - '0';
if (d > 9 || d < 0)
d += '0' - 'A' + 10;
if (d > 15 || d < 0)
d += 'A' - 'a';
if (d > 15 || d < 0)
return -1;
n <<= 4;
n |= d;
}
return n;
}
It should handle digits in both cases, and work for both ASCII and EBCDIC. Using it for more than 7 digits invites integer overflow, and may make the use of -1 as an error value indistinguishable from a valid conversion.
Just call it with the offset added to the base string: e.g. w = hexdigits(buf+3, 4); for the suggested offset of 3 chars into a string stored in buf.
Edit: Here's a version with fewer conditions that is guaranteed to work for ASCII. I'm reasonably certain it will work for EBCDIC as well, but don't have any text of that flavor laying around to prove it.
Also, I fixed a stupid oversight and made the accumulator an int instead of unsigned short. It wouldn't affect the 4-digit case, but it made it overflow at only 16-bit numbers instead of the full capacity of an int.
int hexdigits2(char *str, int ndigits)
{
int i;
int n = 0;
for (i=0; i<ndigits; ++i) {
unsigned char d = *str++ - '0';
if (d > 9)
d += '0' - 'A' + 10;
if (d > 15)
d += 'A' - 'a';
if (d > 15)
return -1;
n <<= 4;
n |= d;
}
return n;
}
Usage is the same as the earlier version, but the generated code could be a bit smaller.
Here's my own try at it now that I thought about it for a moment - I'm not at all sure this is the best, so I will wait a while and then accept the answer that seems best to me.
val = 0;
for (i = 0; i < 4; i++) {
val <<= 4;
if (ptr[offset+i] >= '0' && ptr[offset+i] <= '9')
val += ptr[offset+i] - '0';
else if (ptr[offset+i] >= 'a' && ptr[offset+i] <= 'f')
val += (ptr[offset+i] - 'a') + 10;
else if (ptr[offset+i] >= 'A' && ptr[offset+i] <= 'F')
val += (ptr[offset+i] - 'A') + 10;
else {
/* signal error */
}
}
/* evaluates the first containing hexval in s */
int evalonehexFromStr( const char *s, unsigned long *val )
{
while( *s )
if( 1==sscanf(s++, "%04lx", val ) )
return 1;
return 0;
}
It works for exactly 4 hex-digits, eg:
unsigned long result;
if( evalonehexFromStr("foo10a4bar", &result) )
printf("\nOK - %lu", result);
If you need other hex-digit sizes, replace "4" to your size or take "%lx" for any hexval for values up to MAX_ULONG.
Code
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int offset = atoi(argv[2]);
argv[1][offset + 4] = '\0';
printf("%lu\n", strtol(argv[1] + offset, NULL, 0x10));
}
Usage
matt#stanley:$ make small_hex_converter
cc small_hex_converter.c -o small_hex_converter
matt#stanley:$ ./small_hex_converter f0010a4bar 3
4260

Resources