reading bytes to a variable....

ceus's Avatar, Join Date: Oct 2006
Go4Expert Member
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...
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
read them into 2 char and then combine them using sprintf.
ceus's Avatar, Join Date: Oct 2006
Go4Expert Member
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...
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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
ceus's Avatar, Join Date: Oct 2006
Go4Expert Member
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 ??
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Thats why I mentioned convert them to int.
ceus's Avatar, Join Date: Oct 2006
Go4Expert Member
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 ???
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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.
ceus's Avatar, Join Date: Oct 2006
Go4Expert Member
thanks shabbir...
but if the value is 3A i have to read that as 16*3+10=58..... how can i do this....
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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.