我已经声明了一个数组

Buffer[0]='0'
Buffer[1]='1'
Buffer[2]=' '
Buffer[3]='0'
Buffer[4]='5'

我只想把这些值转换成整数例如:
char Buffer[100]="01 05 01 4A 63 41";Buffer[0]='0'到0x01(1)
Buffer[1]='1'Buffer[0]='0'到0x05(5)
... 等。
Buffer[1]='5'无法使用,因为它将所有atoi()值转换为整数。
如何将特定的空格分隔值子字符串转换为整数?

最佳答案

考虑一下:

#include <stdio.h>

int main()
{
    char Buffer[100] = "01 05 01 4A 63 41" ;
    const char* h = &Buffer[0] ;
    int i ;

    while( *h != 0 )
    {
        if( sscanf( h, "%2x", &i  ) == 1 )
        {
            printf( "0x%02X (%d)\n", i, i ) ;
        }

        h += 3 ;
    }

   return 0;
}

其输出为:
0x01 (1)
0x05 (5)
0x01 (1)
0x4A (74)
0x63 (99)
0x41 (65)

I have assumed that all the values are hexadecimal, all two digits, and all separated by a single space (or rather a single non-hex-difgit character), and that the array is nul terminated. If either of these conditions are not true, the code will need modification. For example if the values may be variable length, then the format specifiers need changing, and, you should increment h until a space or nul is found, and if a space is found, increment once more.

You could write similar code using strtol() instead of sscanf() for conversion, but atoi() is specific to decimal strings, so could not be used.

If you are uncomfortable with the pointer arithmetic, then by array indexing the equivalent is:

#include <stdio.h>

int main()
{
    char Buffer[100] = "01 05 01 4A 63 41" ;
    int c = 0 ;
    int i ;

    while( *h != 0 )
    {
        if( sscanf( &Buffer[c], "%2x", &i  ) == 1 )
        {
            printf( "0x%02X (%d)\n", i, i ) ;
        }

        c += 3 ;
    }

   return 0;
}

如果您愿意,还有strtol()版本:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char Buffer[100] = "01 05 01 4A 63 41" ;
    const char* h = &Buffer[0] ;

    while( *h != 0 )
    {
        int i = strtol( h, 0, 16 ) ;
        printf( "0x%02X (%d)\n", i, i ) ;

        h += 3 ;
    }

   return 0;
}

关于c - 将特定的数组元素转换为整数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19477897/

10-15 00:13
查看更多