HLSL array gives bad value when indexed with variables

Kind of a weird situation so I’ll try to explain as best I can:

I’m writing a compute shader in HLSL to implement Marching Cubes. Part of this algorithm includes OR’ing an integer to flag which vertices are inside/outside of a surface. This integer (flagIndex) is then used as the index into a constant array / lookup table which returns another integer used to flag which edges of the cube have intersections. Here’s the relevant code:

// Flag which vertices are inside or outside the surface
uint flagIndex = 0;
for (vertIndex = 0; vertIndex < 8; vertIndex++)
{
    if (cubeValue[vertIndex] <= targetValue)
    {
        flagIndex |= 1 << vertIndex;
    }
}

// Find which edges are intersected by surface
uint edgeFlags = cubeEdgeFlags[flagIndex];

// Return if no intersections present
if (edgeFlags == 0)
    return;

The issue arises when trying to evaluate cubeEdgeFlags[flagIndex]. When flagIndex is a non-zero value, the expression evaluates as expected. When flagIndex is zero, though, it returns a nonsensical value from the array, even though cubeEdgeFlags[0] = 0.

If I directly access cubeEdgeFlags[0], or access it using a new integer set to zero, I get the expected result (0). If I access cubeEdgeFlags[flagIndex], even when flagIndex is equal to zero (confirmed by printing out flagIndex), I get a nonsensical value of like 107243000 or something around there.

A similar issue also occurs when accessing other arrays, for instance, I have the following condition later in the shader:

if (triangleConnectionTable[flagIndex][3 * triIndex] < 0)
            break;

I just recently realized this condition isn’t working as expected, because even when flagIndex and 3 * triIndex SHOULD index to a negative value in the triangleConnectionTable, they return a different nonsensically high number, something like 4097209403… etc. If I print the values of flagIndex and 3 * triIndex, then manually insert those values in place of the variables (i.e. type out triangleConnectionTable[240][12]), I still get the nonsensical value. So something is clearly messed up with my arrays, but I don’t know what!

Does anyone have any idea what is going on? This has been driving me nuts and I feel like it’s also influencing other areas of my shader so it’s essential I get this sorted out! Thank you!

I’m rusty on my negative integer representation in binary, but I would say that it’s related to how negative numbers are stored. If the type is uint and you try to put a negative value in there, technically it’s a huge number because the first bit is on (to indicate a negative number), plus the number is a bit complement or something like that, so the bits are flipped.

Try using ints, if you need the negative numbers.