How do you read in a 3 byte size value as an integer in c++?
15,345
Solution 1
Read each byte and then put them together into your int
:
int id3 = byte0 + (byte1 << 8) + (byte2 << 16);
Make sure to take endianness into account.
Solution 2
Read the bytes in individually, and put them into the correct places in an int:
int value = 0;
unsigned char byte1 = fgetc(ID3file);
unsigned char byte2 = fgetc(ID3file);
unsigned char byte3 = fgetc(ID3file);
value = (byte1 << 16) | (byte2 << 8) | byte3;
Edit: it appears that ID3 uses network (big-endian) byte order -- changed code to match.
Solution 3
If your process is computation intensive, and you want to save time (esp. if you are doing embedded systems), my suggestion will be to use union/struct. This takes away the load of left shift and right shift.
union{
unsigned int ui32;
struct{
unsigned char ll;
unsigned char lh;
unsigned char hl;
unsigned char hh;
}splitter;
}combine;
combine.splitter.ll = 0x78;
combine.splitter.lh = 0x56;
combine.splitter.hl = 0x34;
combine.splitter.hh = 0x12;
printf("This is the combined Value: %d", combine.ui32);
This Should work. If anyone feels this should not be used, please let me know the reason.
Cheers! Aditya
Author by
carboncomputed
Updated on June 19, 2022Comments
-
carboncomputed almost 2 years
I'm reading in an id3 tag where the size of each frame is specified in 3 bytes. How would I be able to utilize this value as an int?