将十进制转换为字符/字符串

标签 c string char decimal

假设我有这个号码

int x = 65535;

这是以下的十进制表示:

ÿÿ

我知道如何从一个字符中做到这一点

#include <stdio.h>

int main() {
    int f = 65535;
    printf("%c", f);
}

但这只会给我“ÿ”

我想在不使用任何外部库的情况下执行此操作,最好使用 C 类型字符串。

最佳答案

#include <stdio.h>

int main() {
    unsigned f = 65535; // initial value

    // this will do the printf and ff >>= 8 until f <= 0 ( =0 actually)
    do {
      printf("%c", f & 0xff); // print once char. The &0xff keeps only the bits for one byte (8 bits)
      f >>= 8; // shifts f right side for 8 bits
    } while (f > 0);
}

考虑值 65535,或十六进制的 0xffff,这意味着它的正值占用 2 个字节,即 0xff 和 0xff

  • f & 0xff 的打印仅保留 8 LSb,(0xffff & 0xff = 0xff)
  • f >> = 8 将值右移 8 位,0xffff 变为 0x00ff(右侧的 'ff' 消失了
  • f > 0 为真,因为 f == 0xff 现在

下一个循环是一样的,但是f >>= 8 将 0x00ff 右移 => 0x0000,f 为空。 因此 f > 0 条件错误,循环结束。

关于将十进制转换为字符/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14476119/

相关文章:

c - 函数有 malloc 语法错误?

Python:将复杂的字符串解析成可用的数据进行分析

c++ - 括号之间的两个字符串在 C++ 中用逗号分隔

c - strlen 数组有不同的结果

在循环中收集字符串并打印出循环外的所有字符串

mysql - 使用 varchar 作为主键有什么限制?

c - 如何在C中使用 "anonymous"管道进行进程同步?

c - 在不创建特定管道描述符的情况下进行管道传输

c - 有没有办法在 C 中表达 int 的数学模块?

c - 错误地复制到结构中