Converting char to unsigned int

Hello,

I have a character array containing hexadecimal digits, and I need to convert it into an unsigned integer. I thought there must be a way to do this, if the character array is a variable.

Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
   

   int htoi ( char s[] )

 {

  if (isxdigit(s[i]))

  return (unsigned int) s[i] << char *  s[i]

 }



Am I on the right track?
Last edited on
Use the library? http://en.cppreference.com/w/c/string/byte/strtol

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <string.h>

unsigned int htoui( const char* restrict hexdigits )
{
    if( hexdigits == NULL ) { errno = EINVAL ; /* bsd */ return 0 ; }
    
    // http://en.cppreference.com/w/c/string/byte/strtoul
    char* p = NULL ;
    errno = 0 ;
    const unsigned long v = strtoul( hexdigits, &p, 16 ) ;

    if( errno != 0 ) return 0 ; // strtol failed
    
    if( *p != 0 ) { errno = EINVAL ; /* bsd */ return 0 ; } // not fully parsed
    
    if( v > UINT_MAX ) { errno = ERANGE ; return 0 ; } // out of range

    return v ;
}

int main()
{
    const char* const test[] = { "ffff", "0x82345678", "123", "123x", "0x1234567890ab", NULL } ;
    enum { N = sizeof(test) / sizeof(*test) }; 
    
    for( int i = 0 ; i < N ; ++i )
    {
        unsigned int value =  htoui( test[i] ) ;
        printf( "str: '%s' int: %u 0x%x (status: %s)\n", ( test[i] ? test[i] : "NULL" ), value, value, strerror(errno) ) ;
    }
}

http://coliru.stacked-crooked.com/a/aa6e461e9f42be7a
Hi,

I just tried to implement something myself. Can`t I just use binary operators to do the conversion?

I see here https://msdn.microsoft.com/en-us/library/fc9te331.aspx

With integral promotion, you can use the following in an expression wherever another integral type can be used:

Objects, literals, and constants of type char and short int.

So it would suggest something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14


int htoi ( char s[] )

 {

  if ( isxdigit(s[i]) )  {

  unsigned int val = (unsigned char)s[i] << char * s

  return val;

 }
Last edited on
Topic archived. No new replies allowed.