c - Char array to unsigned short conversion issue -


i trying convert char array unsigned short not working should.

char szascbuf[64] = "123456789123456789123456789";  int storetoflash(char szascbuf[], int startaddress) {    int ictr; int errorcode = 0; int address = startaddress; unsigned short *us_buf = (unsigned short*)szascbuf;           // write flash for(ictr=0;ictr<28;ictr++) {        errorcode = flash_write(address++, us_buf[ictr]);     if((errorcode &0x45)!= 0)     {       flash_clearerror();               } } return errorcode; } 

when see conversion, on us_buf[0] have value 12594, us_buf[1]= 13108 , have values uptous_buf[5]` after "0" remaining address. have tried declare char array also

char szascbuf[64] = {'1','2','3','4','5','6','7','8','9','1',.....'\0'}; 

i passing parameters function

storetoflash(szascbuf, flashpointer); //flashpointe=0 

i using iar embedded workbench arm. big enedian 32. suggestions doing wrong?

thanks in advance.

reinterpreting char array szascbuf array of short not safe because of alignment issues. char type has least strict alignment requirements , short stricter. means szascbuf might start @ address 13, whereas short should start @ either 12 or 14.

this violates strict aliasing rule, since szascbuf , us_buf pointing @ same location while having different pointer types. compiler might perform optimisations don't take account , manifest in nasty bugs.

the correct way write code iterate on original szascbuf step of 2 , bit-twiddling produce 2-byte value out of it:

for (size_t = 0; < sizeof(szascbuf); += 2) {     uint16_t value = (szascbuf[i] << 8) | szascbuf[i + 1];     errorcode = flash_write(address++, value);      if (errorcode & 0x45) {         flash_clearerror();               } } 

if intended treat digit characters numeric value, it:

uint16_t value = (szascbuf[i] - '0') + (szascbuf[i + 1] - '0'); 

in case want numeric value of each character in 2-byte value (1, 2, 3, 4, ...), iterate on array step of 1 , fetch way:

uint16_t value = szascbuf[i] - '0'; 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -