【问题标题】:Trouble with converting dec into hex for C无法将 dec 转换为 C 的十六进制
【发布时间】:2011-04-17 06:34:14
【问题描述】:

仅使用以下库:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <math.h>

我需要一种将十进制转换为十六进制的有效方法:

int iteration (arguments...) {
//calculate the number of iterations for this function to do something
return iterations; //returns in decimal, e.g. 70
}

char hello = (iteration in hex);

(十六进制迭代)的代码是什么样的?

我有很多循环,所以会有很多转换为十六进制,效率越高越好(尽管我很确定有一个函数可以做到这一点)。

【问题讨论】:

  • 你认为hello的类型会是什么?
  • 我什至无法弄清楚您在阅读该内容时要做什么。
  • 十六进制不是一种类型,它只是一种不同的计数方式,和/或一种格式化数字数据以供打印的方式。 46 十六进制 = 70 十进制。除非我错过了什么......
  • 我很抱歉@Brain...这是一个深夜,我很紧张:(

标签: c hex


【解决方案1】:

没有像将int 作为小数返回这样的事情。 int 在 C 中有一个内部表示,这与我们为人类表示数字的方式没有太大关系。

在 C 中,您可以将用八进制、十进制或十六进制表示的数字分配给 int。然后它包含可以说的“抽象”数字。

int a = 073; // starting with 0, interpreted as octal
int b = 23;  // starting with another digit, decimal
int c = 0xA3 // starting with 0x, hexadecimal

【讨论】:

    【解决方案2】:

    如果我理解你的问题,我相信你想要的是 printf("%x", 迭代); 或者 printf("%X", 迭代);

    【讨论】:

      【解决方案3】:

      整数的最后一个字节可分配给char

      char hello = iteration(...) & 0xff;
      

      至于其余,一个数字就是一个数字; “转换”为十六进制只对输出很重要。

      【讨论】:

        猜你喜欢
        • 2017-07-31
        • 2013-07-20
        • 2012-06-17
        • 2014-06-18
        • 2017-11-13
        • 2011-08-04
        • 2015-01-09
        • 1970-01-01
        • 2021-06-26
        相关资源
        最近更新 更多