Search code examples
ccharcpu-registers

How does char data type represent in 32-bit registers?


I understand that int and other 32-bit data types fit in a register. However, I didn't understand what happens when our data type, like char which is 1 byte, is smaller than 32 bits. Like in char example, what happens to the rest of 24 bits? Does it pad with all 0s? Isn't it too small to represent in a word?


Assume that I have a C program with a char variable. How does it represent in register?


Solution

  • If the CPU allows segmented register access (eg to the word, byte) it may just use the byte sub register. If the CPU is strictly 32 bit your byte goes into bits 0-7. Depending on the destination usage it may or may not mask out the rest of it to 0. (AND reg,0x000000FF) if the destination code works with the register as wholes. There are too many variables and much open-endedness to give you a black an white answer.

    utilizing 0xFF as a byte register and 0x000000FF as a d-word register are identical to the opcodes that would use them if they had separate byte and dword couterparts. Unless they are bit-specific ops like "branch if high bit set", or bit rotation/shifting. If signed, 0xFF would expand to 0xFFFFFFFF (or 0x83 to 0xFFFFFF83)

    Edit to the update: C representing a char in a register would indeed zero the rest out, depending on the compiler it may ZERO the register first before setting bits 0-7 or it may perform as explained above. When signed, the sign bit needs to extend so 0 the register, NEG it and set 0-7. Some CPU even have an op explicitly for sign-expanding.