Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this line obfuscated?

Tags:

c

In this snippet,

if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
{
    /* statements */
}  

the member OscillatorType could have any of the values, or their combination, defined below.

#define RCC_OSCILLATORTYPE_NONE            ((uint32_t)0x00000000)
#define RCC_OSCILLATORTYPE_HSE             ((uint32_t)0x00000001)
#define RCC_OSCILLATORTYPE_HSI             ((uint32_t)0x00000002)
#define RCC_OSCILLATORTYPE_LSE             ((uint32_t)0x00000004)
#define RCC_OSCILLATORTYPE_LSI             ((uint32_t)0x00000008)  

Why is the if written this way? Why not simply like this?

if(RCC_OscInitStruct->OscillatorType == RCC_OSCILLATORTYPE_HSI)

like image 931
Sohail Avatar asked Dec 04 '22 04:12

Sohail


2 Answers

RCC_OscInitStruct->OscillatorType is a collection of bits packed in an integer value, each bit representing one of the values (RCC_OSCILLATORTYPE_HSE, ...). That's why they come in powers of 2. The code you showed just checks if the bit associated with RCC_OSCILLATORTYPE_HSI is set. It's very probable that bits of other values are also set.

For example if the binary representation of OscillatorType is 0...011, the first and second bit is set, meaning that the RCC_OSCILLATORTYPE_HSE and RCC_OSCILLATORTYPE_HSI values are selected.

like image 188
JuniorCompressor Avatar answered Dec 25 '22 16:12

JuniorCompressor


It's a very common C idiom and not obfuscated in any way. Those are two very different tests.

if ((RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)

says "if the RCC_OSCILLATOR_HSI bit is 1". It doesn't care whether any of the other bits are 0 or 1, whereas

if (RCC_OscInitStruct->OscillatorType == RCC_OSCILLATORTYPE_HSI)

says "if the RCC_OSCILLATOR_HSI bit is 1 AND all the other bits are 0".

like image 31
Ferruccio Avatar answered Dec 25 '22 16:12

Ferruccio