cstm32f4stm32cubeide8-bit

How to read a whole uint_8 variable?


I have a 8 bit variable received_control. This variable should store some 8 bit data. In my use case, I need be able to read all the bits, even those that are 0. Problem is that if my most significant bit value is 0, it won't get stored in my variable.

Variable in question:

  uint8_t received_control = (0 << 0) |
                             (1 << 1) |
                             (0 << 2) |
                             (1 << 3) |
                             (0 << 4) |
                             (1 << 5) |
                             (0 << 6) |
                             (0 << 7);

Output from debugger (via watcch expression)

Name : received_control
Details:42 '*'
Default:42 '*'
Decimal:42
Hex:0x2a
Binary:101010
Octal:052

I'm using a STM32F407 and I program it in STM32CubeIDE. I was curious if there is integrated solution within C, as the solutions I saw online were not suitable.


Solution

  • it won't get stored in my variable

    This is not true. You have some misconception about how variables work. An 8 bit integer variable always holds 8 bits. No matter what value you assign to it, there will be 8 bits.

    If your statement was correct, what value would you assume, these bits should hold after your assignment? As they are present in the variable, they must have some value. And for integer variables, the more significant bits are simply set to 0 or 1 depending on signedness of the variable and the assigned value.

    What you observed is not related to storing data in a variable but it is about a visual representation of that value. You told printf to print an integer variable in binary representation. Normally, printf takes as few characters for printing as possible. If you print as hexadecimal, it will not print 000000002A but only 2A. Unless for some formatting purposes, these leading 0 don't serve any purpose. Therefore you must explicitely ask for it if you want to get more than minimum digits.