c - 为什么我的十六进制转换功能差了一个?

标签 c

我正在尝试学习 c 并且很困惑为什么我的十六进制到整数转换函数返回的值相差一个。

注:0XAAAA == 46390

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

unsigned int hex_to_int(char hex[4]);

int main()
{
    char hex[4] = "AAAA";

    unsigned int result = hex_to_int(hex);
    printf("%d 0X%X\n", result, result);
    return 0;
}    

unsigned int hex_to_int(char input[4])
{
    unsigned int sum, i, exponent;

    for(i = 0, exponent = 3; i < 4; i++, exponent--) {
        unsigned int n = (int)input[i] - 55;
        n *= pow(16, exponent);
        sum += n;
    }   
    return sum;
}

输出:

46391 0XAAAB

更新:我现在意识到“- 55”是荒谬的,看到这个我已经失忆了:

if (input[i] >= '0' && input[i] <= '9')
    val = input[i] - 48;
else if (input[i] >= 'a' && input[i] <= 'f')
    val = input[i] - 87;
else if (input[i] >= 'A' && input[i] <= 'F')
    val = input[i] - 55;

最佳答案

您有几个错误,例如字符串没有以空值终止,ASCII 到十进制的转换是无意义的(值 55?),您没有初始化 sum 等等。只需这样做:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char x[] = "AAAA";

  unsigned int sum = strtoul(x, NULL, 16);
  printf("%d 0X%X\n", sum, sum);
  return 0;
}    

编辑

如果您坚持手动执行此操作:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

unsigned int hexstr_to_uint(const char* str);

int main()
{
  char x[] = "AAAA";

  unsigned int sum = hexstr_to_uint (x);
  printf("%d 0X%X\n", sum, sum);
  return 0;
}    

unsigned int hexstr_to_uint(const char* str)
{
  unsigned int sum = 0;

  for(; *str != '\0'; str++)
  {
    sum *= 16;
    if(isdigit(*str))
    {
      sum += *str - '0';
    }
    else
    {
      char digit = toupper(*str);
      _Static_assert('Z'-'A'==25, "Trash systems not supported.");
      if(digit >= 'A' && digit <= 'F')
      {
        sum += digit - 'A' + 0xA;
      }
    }
  }
  return sum;
}

关于c - 为什么我的十六进制转换功能差了一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47828836/

相关文章:

c - C语言中如何获取从缓存中读取的字节数

c - Windows.h 和 clang (LLVM)

c - 将 8 字节数字写入文件后如何读回?

c - 即使分配了大堆栈大小,如何消除堆栈溢出错误?

c++ - Linux 中伪终端的读写问题

c - 关闭 Linux 套接字后奇怪的程序行为

objective-c - Objective-C 中的 C 风格数组

c - 根据空格划分 char 数组中的字符

c - 如何解析 "CreateProcess"创建的子进程的输出字符串

c - 什么范围的机器的二进制兼容性?