0

I am trying to understand this C code which is supposed to take an integer input value and convert it to a binary number for encryption purposes. For some reason, a static int is declared without initialization and then on the subsequent line it is checked to see it is divisible by 32? The X2 variable is an integer array with a length of 32 that gets modified by this function. Why is the divisibility check done on an uninitialized static int? And what if it is not divisible by 32? It might a billion and if it is not divisible by 32, the function would use it as an index into an array that has a length of 32, which would cause the program to crash. And then at the end i is incremented by 4? Why 4? This function is not making any sense to me. Does this code make sense to anybody?

int ToBits(int value)
{
    int k, j, m;
    static int i;
    if(i % 32 == 0)
        i = 0;
    for (j = 3; j >= 0; j--)
    {
        m = 1 << j;
        k = value & m;
        if(k == 0)
            X2[3 - j + i] = '0' - 48;
        else
            X2[3 - j + i] = '1' - 48;
    }
    i = i + 4;
}
Derek Edwards
  • 11
  • 1
  • 5
  • static variables are initialized to 0 by default – user253751 Apr 15 '19 at 00:43
  • This simply looks like the result of a horrible refucktoring. `i` is just set to zero the first time the function is called. The next time it will have value 4 etc. More explanation [here](https://www.geeksforgeeks.org/static-variables-in-c/) (you should be able to look up such things yourself, the static variable is really only the one strange thing in there). Horrible code; code that is not self-explanatory should have comments to at least indicate *what* the code does. Calling it `nibbleToBits` would be better (are you using tinyAES?) – Maarten Bodewes Apr 16 '19 at 10:32
  • (yeah, `'0' - 48` is soooo much more clear than just writing `0`, sigh) – Maarten Bodewes Apr 16 '19 at 10:37
  • For more info why this is a fucked up way of doing things [see this Q/A](https://stackoverflow.com/questions/7280877/why-and-how-does-gcc-compile-a-function-with-a-missing-return-statement) about the missing `return`. – Maarten Bodewes Apr 16 '19 at 10:41

0 Answers0