Complicated

I have found this code and want to decompose it. I know what it does(Detect color/monochrome monitor) but i need to understand it
1
2
3
4
5
6
7
8
9
10
11
12
/* 
    Video card mono/colour detection.
    Return values:  false=colour
                    true=monochrome
*/
_Bool detectVideoType(void)
{
    char c=(*(volatile USHORT*)0x410)&0x30;
 
    //c can be 0x00 or 0x20 for colour, 0x30 for mono.
    return (c==0x30);
}


what are all the asterisks for and the volatile keyword what does it do
The volatile keyword indicates that an object so qualified is located at an address that is mapped to an I/O port (or some similar non-memory resource).

This fragment takes the number 0x410, which is apparently an MMIO port on whatever platform this was written for. Then it constructs a pointer with the type "pointer to a volatile USHORT" out of that address, using the cast expression (volatile USHORT*)0x410 (assuming USHORT means unsigned 16-bit type, this is equivalent to reinterpret_cast<volatile std::uint16_t*>(0x410) in C++)

Then, the program dereferences that pointer with the asterisk: this operation reads two bytes from the memory-mapped I/O ports 0x410 and 0x411.

Then it uses bitwise AND to pick out two bits (mask 0x30) from the result.

Then it stores the resulting value in a char, which truncates it to a single byte, which is then compared with one of the possible values.

PS: I see, this code fragment is from OSDev wiki and it's reading the BIOS data on a PC in real mode. volatile qualifier isn't strictly necessary, but works to be on the safe side. Either way, it's unlikely that you can encounter a platform where this test is necessary.
Last edited on
Topic archived. No new replies allowed.