bitwise anding unsigned long with 0xffffffff [closed]

微笑、不失礼 提交于 2019-12-11 05:32:38

问题


Below is some code from switch statement. getvalue() returns an unsigned long. Could somebody explain why value is bitwise anded with 0xffffffff. The mcu is 32 bit.

#define WriteMemory(A,V) *(volatile unsigned long*)(A)=(V)
static unsigned value;

case 'b':
value = getvalue();
value &= 0xffffffff;
WriteMemory(2147455555, value);
break; 

回答1:


unsigned long isn't guaranteed to be 32 bit by the C standard. It is only guaranteed to be able to hold 32 bit values.

and-ing it with 0xffffffff makes sure any bits over the 32 are zeroed out.




回答2:


The code uses what's sometimes called "naive/sloppy typing", meaning that it uses the basic int and long types from standard C. Those types are problematic and often non-portable, as they have implementation-defined size.

Because of the implementation-defined size, they pedantically mask out the lower 32 bits, in case int would for some reason turn up as 64 bits on some exotic system.

However, professional programs always use types of known size and signedness from stdint.h. This is particularly true for professional embedded systems.

The same code could be rewritten in much safer and portable ways as:

#include <stdint.h>

#define WriteMemory(A,V) ( *(volatile uint32_t*)(A)=(V) )
static uint32_t value;

case 'b':
value = getvalue();
WriteMemory(2147455555, value);
break; 

uint32_t solves all problems: there's no longer any doubt how big the various types are, so it would be completely superfluous to mask with the lower 32 bits. Nor do you have to worry about implicit type promotions, given that this is a 32 bit system.

(Note the extra parenthesis in the macro, which is necessary to avoid classic macro operator precedence bugs such as x = WriteMemory(2147455555, value) + y; Bug: writes value+y which was probably not intended.)

Another much bigger concern here though, is if the given system will allow a misaligned 32 bit write at address 2147455555. Looks very fishy.



来源:https://stackoverflow.com/questions/39143107/bitwise-anding-unsigned-long-with-0xffffffff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!