So I'm trying to get the sum of the values in a buffer, however, the values need to be rearranged in order to do so. Essentially how do I get C to convert the values in this array:uint16_t inp[] = {0xFF,0x81,0xFD,0x00,0x00,0x00,0x00,0x08,0x00,0x00};
to look like this array: uint16_t buff[] = {0x81FF,0x00FD,0x0000,0x0800,0x0000}
Asked
Active
Viewed 565 times
0

rob ell
- 45
- 7
-
Maybe you should use a loop? – wildplasser Oct 28 '20 at 20:34
-
`buff[0] = ((inp[1] & 0xff) << 8) | (inp[0] && 0xff)`. Generalise and put into a loop. – kaylum Oct 28 '20 at 20:35
-
Are you sure the original form is big-endian? – tadman Oct 28 '20 at 20:36
-
Do you want the array formatted differently if the platform itself is big-endian vs little-endian? That is, are just trying to flip the bytes consistently regardless of platform? Or are you trying to flip the bytes to match the platform? – selbie Oct 28 '20 at 20:38
-
@kaylum thank you! i did a bit of a variation but you gave me what I needed to understand it – rob ell Oct 28 '20 at 20:48
1 Answers
0
Thanks to @kaylum, I figured it out:
#include <stdio.h>
#include <stdint.h>
uint16_t inp[] = {0xFF,0x81,0xFD,0x00,0x00,0x00,0x00,0x08,0x00,0x00};
uint16_t buff[sizeof(inp)/2];
int main(){
int sum = 0;
for(int i = 0; i < sizeof(buff);i=i+2){
buff[i] = ((inp[i+1] | 0x00) << 8) | (inp[i] | 0x00);
//printf("%.4X\n",buff[i]);
}
for(int i = 0; i < sizeof(buff);i++){
sum = sum += buff[i];
}
printf("%u\n",sum);
return 0;
}

rob ell
- 45
- 7
-
`sum = sum += buff[i];` - what's that? I guess you wanted either `sum += buff[i];` or `sum = sum + buff[i];` – Eugene Sh. Oct 28 '20 at 20:54
-
`| 0x00` is redundant. It says "if original bit is 0 make it 0, if the original bit is 1 make it 1". That is, it does nothing and removing it will not change the result at all. – kaylum Oct 28 '20 at 20:55
-
`for(int i = 0; i < sizeof(buff);i++){` <<-- sizeof(buff) is too large. – wildplasser Oct 28 '20 at 21:08