I am a beginner in programming Is there a way to read a midi file in its hex numbers?
I searched the internet that midi files are composed of headers and their contents are in hex numbers like 4D 54 68 64 0A ....
So, what is the best way to extract those hex numbers from a midi file? If there is a C++ library to do this? (I want to write the program in C++ language)
For context, I want to put these hex numbers into an array and replace some of those hex numbers (of course according to the midi file format, so the midi file isn't corrupted) and save it back into a midi file. Like doing some kind of steganography
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.
Update: Just thought I'd mention: The more C++ way to read bytes from a file is using the ifstream
or fstream
classes, and their get()
method, e.g.:
ifstream myFile("file.mid");
int16_t twoByteNum = 0;
myFile.get(&twoByteNum, sizeof(twoByteNum));
(code written in browser, might not quite compile)
Also: Most calculator apps in a computer have a "hex" mode, and if there's a number on the display while you switch from decimal to hex, it will display the same number in hex.