Thoughts on Ex11 extra credit

Just seeking feedback or thoughts on my approach to this challenge in ex11. I wasn’t really sure about what I did and whether there is a better approach

Extra Credit Challenge

If an array of characters is 4 bytes long, and an integer is 4 bytes long, then can you treat the whole name array like it’s just an integer? How might you accomplish this crazy hack?

My approach

I figured the challenge was to find a way to take the bits of binary representation of each character and put them into the appropriate places of the binary representation of a 4byte/32bit int.

The first approach that came to my mind was to:

  1. Initialise an int to 0 (this will be the final converted string)
  2. Loop through each char of the string
  3. Convert this char to an int
  4. Shift the bits of this int to the appropriate place using a bit shift (ie, shift by 8 bits to move the values one byte over)
  5. Add this int (which is a char converted to an int and bit shifted by one byte) to the initialised int from step 1.

One important detail is the direction that bits are shifted (left or right). Which, as far as I can tell, depends on the order in which memory is read for ints.
Is this what ‘endian’ refers too?

As you’ll see in my code below, I presumed that the first char (ie name[0]) corresponds to the first or lowest bits used to represent an int. This not coincidentally the easiest presumption for the code :slight_smile:.

Another important detail is size of the int (8, 16 or 32 bit). I checked with my debugger that on my system ints are 32 bit.
I presume this is system dependent?

My Code

   char name[4] = {'a'};

   name[0] = 'Z';
   name[1] = 'e';
   name[2] = 'd';
   name[3] = '\0';

   int string_to_int = 0;
   int temp_char_int;
   for (int i = 0; i < sizeof(name); ++i)
   	temp_char_int = name[i] << (i*8);
   	string_to_int += temp_char_int;
   printf("String %s as 32bit int: %d.\n", name, string_to_int);
       // PRINTS: String Zed as 32bit int: 6579546.

The Result

As far as I can tell, teh result I get (6579546) is ‘correct’ (given my presumptions).

I verified this by using my debugger to print out the values of the characters in name in hexadecimal format (eg 0x5a for ‘Z’), which could have been done just as easily with an ASCII table now that I think of it, putting those values side by side into a longer hex value and converting that to decimal on the internet.

That looks like a good way to do it. Your temp_char_int should be initialized to a default value. Always give variables a default value or you will have bugs that are catastrophic. I believe many of the OpenSSL bugs are because of not setting this (and also other simple C mistakes).

1 Like