假设我有这个号码
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/