Reputation: 1002
I am only learning c and I am trying to implement a for loop from an algorithm. I am so so confused in how to implement it, please see my attempt below. Any help or thoughts would be greatly appreciated as I am unsure, does it imply a loop within a loop. Or am I implementing the for loop correctly,
The algorithm states For all possible a = (0,z0,z1,0)
Looop From algorithm
for (z0, z1) = (0x00, 0x00) to (0xff,0xff)
h0 = somemethod( 0x02000000L ⊕ (0x00, z0,z1,0x00)) )
My Attempt
#define WORD32 unsigned int
for (BYTE z = 0x00; z < 0xff; z++)
{
for (BYTE z1 = 0x00; z1 < 0xff; z1++)
{
WORD32 a = (0 << 24 | a1 << 16 | z << 8 | 0);
WORD32 h0 = f(0x02000000L^a);
}
}
So I unsure about the loop and is the below correct
h0 = somemethod( 0x02000000L ⊕ (0x00, z0,z1,0x00)) )
WORD32 a = (0 << 24 | a1 << 16 | z << 8 | 0);
WORD32 h0 = f(0x02000000L^a);
IE how i get
(0x00, z0,z1,0x00)
Update
It is latter ordering: (0, 0), (0, 1), (1, 2), ..., (0, 255), (1, 0), …
It means all possible combinations - the ordering does not matter once you go through them all.
Upvotes: 0
Views: 950
Reputation: 13448
Your approach should almost work, only the variable names, the boundaries (0 <= a <= 0xff
) and the size of the loop variable need correction.
for (int z = 0; z <= 0xff; z++)
{ // inner loop same general approach...
}
Should you ever have a case where you iterate the whole range of numbers and switching to a bigger data type is not an option, a manual break condition at the end of loop can be used. For your loop with BYTE
it could look like this
for (BYTE z = 0; z <= 0xff; z++)
{ // inner loop same general approach, followed by break condition...
if (z == 0xff) break; // next increment would overflow to 0
}
Regarding the content of the inner loop, it can be shortened alot, because the 0x02000000
and the other values don't have any overlapping bytes. (note I write a1
because you do, not because it makes any sense)
WORD32 a = (0 << 24 | a1 << 16 | z << 8 | 0);
WORD32 h0 = f(0x02000000L^a);
// vs same result
unsigned long h1 = f(0x02000000L | a1 << 16 | z << 8);
Even if you need to store a
as intermediate result, 0 << X
isn't anything useful, just write a = a1 << 16 | z << 8
.
So the whole code with correct variable names could look like
for (int z0 = 0; z0 <= 0xff; z0++)
{
for (int z1 = 0; z1 <= 0xff; z1++)
{
unsigned long a = z0 << 16 | z1 << 8;
unsigned long h = f(0x02000000 | a); // using | or ^ doesn't matter
}
}
Upvotes: 1