如何以十进制格式打印64位整数值 [英] How to print 64-bit integer value in Decimal
问题描述
使用32位处理器以十进制格式打印64位整数值的方法应该是什么?
最近被问及面试。
What should be the approach to print a 64 bit Integer value in Decimals with a 32-bit processor ?
Recently asked in an Interview.
推荐答案
为简单起见,假设你有一个8位唯一的
处理器和想要显示16位
无符号数。
假设n
是输入数字,算法可以是(伪代码):
In the sake of simplicity, suppose you have a8-bit-only
processor and want to show a16 bit
unsigned number.
Assumingn
is the input number, the algorithm could be (pseudo code):
- k = 0
- 如果n = 0退出
- r [k] =提醒n div 10
- n = n div 10
- k = k + 1
- goto 2
(其中 div
是整数除法)
最后,数组 r
包含数字的十进制表示的数字(反向)。
当然在给定算法中存在问题:我们必须计算 16
位数的整数除法(和提醒)用仅8位
处理器!
我们可以像手工一样执行此操作,但是时间使用4位换句话说,使用数字的十六进制表示。
让我们尝试在一个例子中做到这一点。
即我们试图将 n = 51728
除以 10
,即 hexadecimalese , 0xCA10
by 0xA
。
0xCA
是最有意义的字节, 0x10
是最不重要的字节。
第一步我们除 0xCA
的高位半字节,即 0xC
by 0xA
,获取 0x1
作为提示, 0x2
作为提醒。
然后我们添加这样的提醒 0xCA
的最低半字节(即 0xA
),以获得 0x2A
并重复这个过程:
(where div
is the integer division)
At the end, the array r
contains the digits of the decimal representation of the number (in reverse order).
Of course there is a problem, in the given algorithm: we have to compute the integer division (and the reminder) of a 16
bit number with a 8-bit-only
processor!
We could perform this operation like we do by hand, but using 4 bits at time, in other word using the hexadecimal representation of the numbers.
Let's try to do it in an example.
Namely we try to divide n = 51728
by 10
, that is, in hexadecimalese, 0xCA10
by 0xA
.
0xCA
is the most significative byte and 0x10
is the least significative byte.
In the first step we divide the upper nibble of 0xCA
, that is 0xC
by 0xA
, obtaining 0x1
as quotient and 0x2
as reminder.
Then we add such reminder to the lowest nibble of 0xCA
(namely 0xA
) in order obtain 0x2A
and repeat the process:
// almost all hexadecimal numbers, here
CA10 |A
---
2A 1 (C/A is 12/10, that is quotient 1, reminder 2)
21 4 (2A/A is 42/10, that is quotient 4, reminder 2)
30 3 (21/A is 33/10, that is quotient 3, reminder 3)
6 4 (30/A is 48/10, that is quotient 4, reminder 8)
因此我们获得了商,即 0x1434
(5172十进制)和提醒 8
,一次最多使用一个字节 。换句话说,我们的仅8位
处理器可以执行它。
hence we have obtained the quotient, namely 0x1434
(5172 in decimal) and the reminder 8
, always working with, at most, a byte at time. In other words, our 8-bit-only
processor can perform it.
你可以尝试
You can try
printf("%I64d",c64);
这篇关于如何以十进制格式打印64位整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!