+ 3

Mystery in C

Can anyone experienced in C please give a little bit of explanation about what happens in this code i got from an old book? I just can't get my head around the thing. https://code.sololearn.com/c5QcNKSFoku0

5th Nov 2018, 12:49 PM
bedawang
bedawang - avatar
7 odpowiedzi
+ 15
If you write "Hello, world!" then the memory would be the same as those 'weird looking' numbers. Lets take the first number for example and remove the 0x: 6c6c6548 The ascii values for H = 48, e = 65, l = 6c, see a pattern yet? The first 4 numbers are stored in little endian, which basically reverses the bytes when stored in memory and the other 4 numbers uses big endian. This would allow the program to work on both architectures ( assuming the #define was correct ). https://en.wikipedia.org/wiki/Endianness A union stores its member variables at the same memory location. If cipher changes value, so does what. The only difference though, is that the underlying bytes are interpreted differently. It's also important that both types have the same size. Each cipher is assigned a number, after assigning, the memory looks like this ( remember that the bytes get switched around ): 48 65 6C 6C 6F 2C 20 77 6F 72 6C 64 21 0A 00 00 what interprets it as a char array ( so it reads 1 byte at a time ), now grab http://www.asciitable.com/ as a reference and see that each byte corresponds to a character, which is the output.
5th Nov 2018, 2:04 PM
Dennis
Dennis - avatar
+ 3
@Dennis i was finishing mine explanation to send. But yours is just perfect
5th Nov 2018, 2:15 PM
Anya
Anya - avatar
+ 2
Note, I posted a byte order detection fix (for gcc on SoloLearn) in the code comments.
6th Nov 2018, 2:12 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
@Ricci Hardiansyah Raynaldhi If you need help please post a new and detailed question in the Q&A section and someone who has knowledge about it will answer. Changing topic here is not appropriate.
6th Nov 2018, 1:25 PM
Dennis
Dennis - avatar
0
aha, long is 4 bytes, char is 1 byte. hence initialization of cypher[4] and what[16]. So, when 6c6c6548 is assigned to cypher[0], 6c is assigned to what[0] and so on... This is such a satisfying code once you see it :) Thanks a lot for clearing that out @Dennis
5th Nov 2018, 7:06 PM
bedawang
bedawang - avatar
- 2
#span
6th Nov 2018, 1:03 PM
Ricci Hardiansyah Raynaldhi
- 2
can you tell me about "array"?
6th Nov 2018, 1:13 PM
Ricci Hardiansyah Raynaldhi