[英]Extract Digits From An Integer Without sprintf() Or Modulo
The requirements of this are somewhat restrictive because of the machinery this will eventually be implemented on (a GPU). 由于最终将在(GPU)上实现的机器,因此对此的要求有些限制。
I have an unsigned integer, and I am trying to extract each individual digit. 我有一个无符号整数,我试图提取每个数字。
If I were doing this in C++ on normal hardware & performance weren't a major issue, I might do it like this: 如果我在C ++中使用普通硬件进行此操作并且性能不是主要问题,我可能会这样做:
(Don't hate on me for this code, it's just a sample to illustrate the method) (不要因为这个代码而讨厌我,这只是一个说明方法的示例)
#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int someVal = 1234;
char stringVal[256] ={0};
sprintf(stringVal, "%016d", someVal);
int digits[16] = {0};
for( int i = 0; i < strlen(stringVal); ++i )
{
digits[i] = stringVal[i] - '0';
}
cout << "Integer Value = " << someVal << endl;
cout << "Extracted Digits = ";
copy( &digits[0], &digits[16], ostream_iterator<int>(cout, "-") );
cout << endl;
return 0;
}
I'm trying to find a method to extract these digits with the following restrictions: 我正在尝试找到一种方法来提取这些数字,但有以下限制:
I'm looking for an algorithm, not necessarily specific code. 我正在寻找一种算法,不一定是具体的代码。 But specific code would be great. 但具体的代码会很棒。 The languages I'm most familiar with that translate well to my target hardware are C++, C and assembler. 我最熟悉的语言很好地转换为我的目标硬件是C ++,C和汇编程序。
Any ideas? 有任何想法吗?
EDIT: Here's an update with the algorithm I implemented based on the comments & links below. 编辑:这是我根据下面的评论和链接实施的算法的更新。 Thanks all. 谢谢大家。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
unsigned someVal = 12345678;
static const unsigned numDigits = 10;
unsigned digits[numDigits] = {0};
for( unsigned i = 0, temp = someVal; i < numDigits; ++i, temp /= 10 )
{
digits[numDigits-i-1] = temp - 10 * (temp/10) /*temp % 10*/;
}
cout << "Integer Value = " << someVal << endl;
cout << "Extracted Digits = ";
copy( &digits[0], &digits[numDigits], ostream_iterator<int>(cout, "-") );
cout << endl;
return 0;
}
Remember that the modulo operator can actually be implemented as: 请记住,模运算符实际上可以实现为:
mod(a, n) = a - n * floor(a / n)
Hence, you can use your favorite modulo based algorithm. 因此,您可以使用自己喜欢的基于模数的算法。 You can simulate floor itself by typecasting. 您可以通过类型转换来模拟地板本身。
值得考虑的是Terje Mathisen。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.