Home > OS >  C adding string and int
C adding string and int

Time:05-31

I have been tasked to rewrite a small program written in C to C#.

But I came across this line that I couldn't understand fully. Is it concatenating the string length to the string or the pointer?

int n = _keyData * int(*(int*)(_chap   strlen(_chap) - 4));

This is the variables:

short _ver = 12;
short _keyData = short(_ver * _ver);
char _chap[100]; // Hold time with format [d-d d:d:d:d]

CodePudding user response:

*(int*)(_chap strlen(_chap) - 4) is a strict aliasing violation. Reinterpreting raw bytes as an int is type punning and is not allowed in C (even though some compilers tolerate it).

To fix it (assuming a little-endian system), you can rewrite it like this:

short _ver = 12;
short _keyData = short(_ver * _ver);
char _chap[100]; // Hold time with format [d-d d:d:d:d]

int len = strlen(_chap);
int x = (int)(((unsigned)_chap[len - 1] << 24) |
              ((unsigned)_chap[len - 2] << 16) |
              ((unsigned)_chap[len - 3] <<  8) |
               (unsigned)_chap[len - 4]);
int n = _keyData * x;

Coincidently, it should be easy to port this to C# now.

  •  Tags:  
  • c# c
  • Related