简体   繁体   中英

Buffer operations with shift and or operations

I'm not very sure of my code and want to improve it.

I receive some datas from SPI (8 bits communication) and store it into a buffer of 8 bits so. To use it, I want to use 32 bits word. I know my first code will work but I'm not sure about the second one, can anyone confirm it ?

uint8_t *regData[5];

spi_xfer(fd, "\x24\xFF\xFF\xFF\xCC", 5, regData, 5);
uint32_t regVal;
regVal = (regData[0]);
regVal += (uint32_t)(regData[1]) << 8; 
regVal += (uint32_t)(regData[2]) << 16; 
regVal += (uint32_t)(regData[3]) << 24; 

The second one :

uint8_t *regData[5];

spi_xfer(fd, "\x24\xFF\xFF\xFF\xCC", 5, regData, 5);
uint32_t regVal;
regVal = (regData[0]) | (uint32_t)(regData[1]) << 8 | (uint32_t)(regData[2]) << 16 | (uint32_t)(regData[3]) << 24;

Thanks a lot for your help !

Brieuc

uint8_t *regData[5];

The regData[] is an array of pointers. If this is intended, to retrieve the value stored at the pointer in the array you need to dereference the pointer .

regVal = *(regData[0]);

Otherwise the operation will assign the address stored at regData[0] to regVal , rather than the value stored at the address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM