c - Working with 48bit on 32bit machine -


i have here 1 small "plc", run on 32bit mcu. biggest variable can define uint32 (unsigned int). i'm reading 1 meter gives me 48bit value in 6 chars (through serial line). have value stored in 2 32bits shifting chars.

t1low = (unsigned int) mybuffer[3] << 24 | (unsigned int) mybuffer[2] << 16 |         (unsigned int) mybuffer[1] <<  8 | (unsigned int) mybuffer[0]; t1high = (unsigned int) mybuffer[5] << 8 | (unsigned int) mybuffer[4]; 

but divide 48bit value 1000 , save 1 32bit (because after divide, give me enough precision).

in theory like

unsigned int result = (t1high << 32 | t1low) / 1000; 

of course doesn't work because of big shift... there way how this?

edit: description of resolution: meter measure in kwh, value given in wh. maximum value 9 999 999, enough save in 32bit. meter 9 999 999 000... need cut 3 zeros @ end..

edit2: right answer given cmaster :) if want put code 2 lines, then:

unsigned int value1; unsigned int value2; unsigned int value3;  value2 += (value1%1000) << 16; unsigned long result = ((value2 / 1000) << 16) | ((value3 + ((value2 % 1000) << 16)) / 1000); 

i'd division in base 2^16: split value 3 16 bit chunks, store in uint32_t variables, following:

uint32_t result1 = value1/1000; uint32_t remainder = value1 - result1*1000; value2 += remainder << 16; uint32_t result2 = value2/1000; remainder = value2 - result2*1000; value3 += remainder << 16; uint32_t result3 = value3/1000; 

of course, formulate loop, doubt it's worth it. method precise can be. drawback is, needs 3 divisions , 2 multiplications, may cause performance issues if computing resources tight.


Comments