在 C 中反转十六进制数的程序

Program to Invert a hexadecimal number in C

我的方法:

第一步。首先我把十六进制数转换成十进制数。 (十六进制到十进制逻辑)

然后我使用 ~ 运算符和 unsigned char 数据类型变量反转十进制数的位。

第 2 步。然后我将该十进制数转换为十六进制数。 (十进制到十六进制逻辑)

因此我得到了倒置的十六进制数。

输入和输出都是十六进制数的字符串。

#include <stdio.h>
#include<string.h>
#include<math.h>
int
main ()
{
  long decimal, qu, rem;
  int k, j = 0;
  char hexa[100];


  int p = 0;
  int dig, temp;
  unsigned char re = 0;
  char hex[32] = "42";      //input
  int len = strlen (hex);
  len--;
  for (int i = len; i >= 0; i--)
    {
      switch (hex[i])
    {
    case 'A':
      dig = 10;
      break;
    case 'B':
      dig = 11;
      break;
    case 'C':
      dig = 12;
      break;
    case 'D':
      dig = 13;
      break;
    case 'E':
      dig = 14;
      break;
    case 'F':
      dig = 15;
      break;
    default:
      dig = hex[i] - 48;
      break;
    }
      temp = temp + dig * pow (16, p);
      p++;
      re = temp;
      re = ~re;
    }

  qu = re;

  while (qu != 0)
    {
      rem = qu % 16;
      if (rem < 10)
    hexa[j++] = 48 + rem;
      else
    hexa[j++] = 55 + rem;
      qu = qu / 16;
    }

  for (k = j; k >= 0; k--)
    {
      printf ("%c", hexa[k]);
    }
  return 0;
}
#include <stdlib.h>
#include <stdio.h>

int main() {
    printf("Please enter some hex: ");
    unsigned int hex;
    // scan input as hex into an integer
    scanf("%x", &hex);
    // truncate the last byte into a char
    unsigned char c = hex;
    // invert it
    c = ~c;
    // print it back out as uppercase hex
    printf("Inverted hex: %02X\n", c);
    return 0;
}

好吧,这也许就足够了。这与您描述的步骤相同,但代码更少。

#include <stdio.h>
#include <string.h>

int main()
{
  char * hex = "42ABE3";
  unsigned dec;

  for(int i = 0; i < strlen(hex); i++) {
    sscanf(hex + i, "%1X", &dec);
    printf("%X", 15 - dec);
  }
}

输出

BD541C

请注意,此代码未检查 sscanf 是否成功,但如果需要,您可以添加它。