reading bytes to a variable....

Go4Expert Member
16Oct2006,20:56   #1
ceus's Avatar
Hi all,
i am new to this forum, and i am a C beginner... can anyone tell me that how to read 2 bytes of data from a file and have that in a single variable ???
thank u...
Go4Expert Founder
17Oct2006,11:01   #2
shabbir's Avatar
read them into 2 char and then combine them using sprintf.
Go4Expert Member
18Oct2006,14:29   #3
ceus's Avatar
thanks for the reply shabbir,
i will tell my problem more specifically.... i have a hex file and i wanted to read 2nd and 3rd bytes of that file which contains some information about some size... i want that size to be extracted in a single variable.....please help me
thanks...
Go4Expert Founder
18Oct2006,15:09   #4
shabbir's Avatar
Read second byte into a char say an array of 2 elements x[0] and 3rd byte into char x[1].

Convert them to int and then combine both the bytes using atoi function
Go4Expert Member
24Oct2006,11:38   #5
ceus's Avatar
thanks shabbir,
i tried that... but by using atoi only integers will be displayed...what if the values stored are in HEX say...A,B....F... atoi function will not recognize this ??? am i right ??
Go4Expert Founder
25Oct2006,10:02   #6
shabbir's Avatar
Thats why I mentioned convert them to int.
Go4Expert Member
25Oct2006,11:23   #7
ceus's Avatar
sorry i didnt get u ???
say i have 3 and A(hex value) in the second and third locations of the file... by using atoi it only recognizes it as 3 ......and A is truncated right ???
Go4Expert Founder
25Oct2006,12:33   #8
shabbir's Avatar
You are reading 3 now convert it to integer. which will be 3.

Now read A, Convert it to int which will be 10

Now combine them using atoi function.

Probably I wasnt clear in my previous post but I think this should.
Go4Expert Member
25Oct2006,12:55   #9
ceus's Avatar
thanks shabbir...
but if the value is 3A i have to read that as 16*3+10=58..... how can i do this....
Go4Expert Founder
25Oct2006,13:47   #10
shabbir's Avatar
I guess it should go like read the string as Hex like 3A. Now convert the 3A using the Decimal, Hex, octal and binary number inter conversion.

3A in Hex is equivalent to 58 in Decimal and so you dont need to go about reading the bytes and then converting.