Processing an Array of Characters as an Integer - Learn C the Hard Way Extra Credit

In Zed Shaw's โ€œLearn the Hard Way,โ€ Exercise 9 ( http://c.learncodethehardway.org/book/ex9.html ) has an additional question that I find interesting. It defines a 4-character array and asks the reader to find out how use an array as a 4-byte integer.

At this point, I know enough to be dangerous, and I thought the answer was something like that:

#include <stdio.h> int main(int argc, char *argv[]) { char name[4] = {'A'}; int *name_int; name_int = &name; printf("%d", *name_int); return 0; } 

My thoughts are that if I created an int pointer with the value being the address of the array, the int type would use the data byte at that address, and then the next 3 bytes of available data. In my limited understanding, I get the impression that both int and array will use memory the same way: starting from an arbitrary memory address, than using the next address in the sequence, etc.

However, the output of this is not what I expected: I get the value of ascii 'A'. Which seems to me that my decision is wrong, my understanding of how memory is processed is wrong, or both.

How can I make this little hack and where am I mistaken? I hope to get away from this in order to better understand how pointers and references work, and how memory is stored and used.

Thanks!

+6
source share
1 answer

You work in little-endian vs big-endian representation of numbers.

Let's look at the 4-btyes values โ€‹โ€‹that are used to represent a 4-byte integer.

  + ---- + ---- + ---- + ---- +
 |  N1 |  N2 |  N3 |  N4 |
 + ---- + ---- + ---- + ---- +

In a large-end view, these 4 bytes represent:

 N1*2^24 + N2*2^16 + N3*2^8 + N4 

In a low-intensity representation, these 4 bytes represent:

 N1 + N2*2^8 + N3*2^16 + N4*2^24 

In your case.

 N1 = 'A' (65 decimal) N2 = 0 N3 = 0 N4 = 0 

Since the value of the whole you get is 65 , you have a little idea of โ€‹โ€‹the end. If you want to process these numbers, for example, a big-endian view, you can use the following:

 #include <stdio.h> int main(int argc, char *argv[]) { int i; char nameString[4] = {'A'}; int name = 0; for ( i = 0; i < 4; ++i ) { name = (name << 8) + nameString[i]; } printf("%d\n", name); printf("%X\n", name); return 0; } 

The output I get with the above code is:

  1090519040
 41000000
+8
source

All Articles