Let me tell you a secret: There are no hex numbers inside your computer. There are also no decimal numbers. All numbers in your computer are stored as binary. Whenever you write a decimal number like 95
in your code, what C++ does is convert it into binary internally and write it to disk as 1011111
.
As such, the problem you're trying to solve needs to be re-phrased. You do not want to read hex numbers, but rather, you want to specify a number as hex in your code (instead of as decimal like usually).
There are various ways to specify a hex number. You could use a calculator to convert the number from hex to decimal, then specify that decimal number in your code (e.g. hex number 4D
is 4 * 16 + 13 == 77
. So when you've read a number, you can then do if (theNumber == 77) ...
).
However, since writing numbers in decimal and hexadecimal is a common thing in programming, C++ actually has a way built in to write hexadecimal numbers. You write your hexadecimal number with a 0x
at the start. So to write 77
in hex, you would write 0x4D
. So once you've read the number from the file, you would do something like if (theNumber == 0x4D) ...
.
There are other bases in which you can specify a number in C++. There is 0b
for binary numbers (so to specify the number exactly how it will be on disk), and if a number starts with just a 0
, C++ thinks it is in octal. So be careful and don't prefix your decimal numbers with zeroes! Because 010 == 8
, it's not 10
!
As to actually reading the data from the file, you do that using the fread()
function.