#Not understanding fwrite() and ints

28 messages · Page 1 of 1 (latest)

tame gulch
#

hi so im getting sooo fucking confused with smth. here is my code

    unsigned int magic_word_array[] = {0x54, 0x41, 0x42, 0x49};
    fwrite(magic_word_array, sizeof(char), MAGIC_SIZE, out_file);

this is writing 0x54 0x00 0x00 0x00 to the file, why?

finite sandalBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

sweet socket
#

what's magic_size

barren topaz
#

Your magic array was likely supposed to contain chars/unsigned chars, no?

sweet socket
#

i'm guessing your magic_size is 4, so it only writes the first int

#

if you wanted to write ints maybe sizeof(char) was supposed to be sizeof(int)

tame gulch
#

yee, well, if i just change it to unsigned char it works

#

but im a bit confused and its relevant to the rest of my code

#

why doesnt fwrite work similarly to smth like fputc? where if i have a unsigned int, itll just use the last 8 bytes of it? or is my understadnginflawed there too

sweet socket
#

you are giving it a pointer

tame gulch
#

AH

#

wait i think i get you

#

so itll be like

#

00 00 00 54 00 00 00 41 00 00 00 42 00 00 00 49

#

so itll start at 54, and then sizeof(char) = 1 byte so itll move along one byte which will just go to 00?

sweet socket
#

yep

tame gulch
#

hm

#

then why does

#

unsigned int magic_word_array[] = {0x54, 0x41, 0x42, 0x49};
fwrite(magic_word_array, sizeof(unsigned int), MAGIC_SIZE, out_file);

#

do 54 00 00 00 41 00 00 00 42 00 00 00 49 in the file?

#

ah

#

that also makes sense now thinking about it

tawny quest
uncut lichen
#

like rhubarb said - x86 is little endian, which means the "littlest" or least significant byte goes on the left end

#

thus short int of value 1 is stored in memory as "01 00"

#

and 256 is "00 01", i.e. you would write it in code as 0x100, but in memory bytes are stored in reverse order

#

(in case "left end" is vague, it is smaller address in memory)