gpt4 book ai didi

c - 什么是一串十六进制数字?

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:19 25 4
gpt4 key购买 nike

既然问题已得到解答,我将使用从这里的每个人那里获得的帮助(谢谢!)发布我的解决方案

我不喜欢的主要事情是假设每个输入都以 '\n' 结尾只是因为我的 linux 终端是这样的!还必须有一种更优雅的方法将 A-F/a-f 转换为十进制,也许使用我自己编写的辅助函数(除了 pow 和 printf 之外还没有访问任何函数)!

我正在做 K&R The C Programming Language, Exercise 2.3:

“编写一个函数 htoi(s),它将十六进制数字串(包括可选的 0x 或 0X)转换为其等效的整数值。允许的数字为 0 到9,a 到 f,A 到 F。”

#include <stdio.h>
#include <math.h>

#define MAXLEN 1000 /* maximum accepted user input is 999 digits */

int htoi( char s[], int maxPower ) ; /* maxPower will be two less than string length (len - 2) because the exponentiation is 0-indexed
* remove the length values which represent '\n' and '\0' in user input
* if the string begins with "0x" or "0X", we remove two more from the power variable inside the htoi() body. */

int main( void )
{
int c, i ;
int len ; /* tracks length of hexString, used to determine exponent value */
char hexString[ MAXLEN ] ;

len = 0 ;
for ( i = 0 ; i < MAXLEN - 1 && ( c = getchar() ) != EOF ; ++i ) {
hexString[i] = c ;
++len ;
}
hexString[len] = '\0' ; /* value of len is one more than termination value of i in above loop */

printf( "Hex String: %s\nInt: %d\n", hexString, htoi( hexString, len - 2 ) ) ;
return 0 ;
}

int htoi( char s[], int power )
{
int j, i, n, decimal ;

n = 0 ;
if ( s[0] == '0' && ( s[1] == 'x' || s[1] == 'X' ) ) { /* cutting off first two array values if string begins with 0x or 0X */
j = 0 ;
while ( ( s[j] = s[j + 2] ) != '\0' ) {
++j ;
}
power = power - 2 ; /* maximum exponent value now represents the usable data */
}

for ( i = 0 ; s[i] != '\n' && s[i] != '\0' ; ++i ) {
if ( s[i] >= '0' && s[i] <= '9' ) {
decimal = s[i] - '0' ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'A' || s[i] == 'a' ) {
decimal = 10 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'B' || s[i] == 'b' ) {
decimal = 11 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'C' || s[i] == 'c' ) {
decimal = 12 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'D' || s[i] == 'd' ) {
decimal = 13 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'E' || s[i] == 'e' ) {
decimal = 14 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else if ( s[i] == 'F' || s[i] == 'f' ) {
decimal = 15 ;
n = ( decimal * pow( 16, power ) ) + n ;
--power ;
} else {
printf( "ERROR 69:\nInput string was not hexidecimal (0-9, A-F, a-f)\nResult is 0!\n" ) ;
n = 0;
return n;
}
}
return n ;
}

最佳答案

意思是像AB0C5342F这样的字符串。用 C 语言来说:

char s[] = "AB0C5342F";

关于c - 什么是一串十六进制数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com