获得每个数字从一个整体的整数 [英] Getting each individual digit from a whole integer

查看:175
本文介绍了获得每个数字从一个整体的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有所谓的分数一个整数,看起来像这样:

Let's say I have an integer called 'score', that looks like this:

int score = 1529587;

现在我想要做的就是让每一位1,5,2,9,5,8,7使用位运算符的分数。我是pretty肯定,这可能因为我曾经用类似的方法,从十六进制颜色值提取红,绿和蓝色值来完成。

Now what I want to do is get each digit 1, 5, 2, 9, 5, 8, 7 from the score using bitwise operators. I'm pretty sure this can be done since I've once used a similar method to extract the red green and blue values from a hexadecimal colour value.

我将如何做到这一点?

修改结果
这并不一定是位运算符,我只是觉得这会是简单的方式。

Edit
It doesn't necessarily have to be bitwise operators, I just thought it'd be simpler that way.

推荐答案

您使用模运算符:

while(score)
{
    printf("%d\n", score % 10);
    score /= 10;
}

请注意,这将让你以相反的顺序位数(即至少显著​​位在前)。如果你想最显著位首先,你必须数字存储在一个数组,然后以相反的顺序读出来。

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.

这篇关于获得每个数字从一个整体的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆