如何生成从0x0到0xffffffff的所有32位数字?

时间:2018-04-15 22:54:43

标签: c 32-bit

我想测试我写的程序的每个可能的有效输入。它接受32位值。那么如何编写一个循环来生成从0x0到0xffffffff的所有输入?我不确定如何增加值(它不会增加1,对吗?)

这是我尝试过的,但我不确定它是否有效:

unsigned int start = 0x0;
while (start < 0xffffffff){
    //do stuff
    start += 0b1;
}

2 个答案:

答案 0 :(得分:5)

您的代码不起作用,因为它没有执行最终值0xFFFFFFFF

如果您将代码更改为:

unsigned int start = 0x0;
while (start <= 0xffffffff){
    //do stuff
    start += 1;
}

然后(对于32位无符号整数)代码将永远循环。

要正确地执行它,您需要一个依赖于溢出的无符号整数的循环,如下所示:

unsigned int start = 0x0;
do {
    //do stuff
    start += 1;
} while(start != 0x0);

答案 1 :(得分:3)

您的代码缺少最大数字

#include "stdafx.h"
#include <iostream>
using namespace std; 

//function prototype 
int getHighest(int numArray[], int numElements); 
int getLowest(int numArray[], int numElements);


int main()
{
    int numbers[4] = { 13, 2, 40, 25 };

    cout << "The highest number in the array is "
        << getHighest(numbers, 2) << "." << endl;
    cout << "The lowest number in the array is "
        << getLowest(numbers, 1) << "." << endl;


    system("Pause");
    return 0;



} // end of main function 

//******function definitions******
int getHighest(int numArray[], int numElements);
int getHighest(int numArray[], int numElements)
{
    return 0;
}
int getLowest(int numArray[], int numElements)
{
    //assign first elemet's value to the high variable
    int high = numArray[0];
    int low = numArray[0];

    //begin search with second element
    for (int sub = 1; sub < numElements; sub += 3)
        if (numArray[sub] > high)
            high = numArray[sub];
    for (int sub = 1; sub < numElements; sub += 1)
    if (numArray[sub] > low)
        low = numArray[sub];

    //end if 
    //end for
    return low; 
    return high;


 //end of getHighest function

    return 0;
}