Parsing a float to an array of uchar C++ -


to fit need of specific programming library, must take float value , store in array comprising of unsigned chars (0-255 range) in c++.

say have

float x = 32.453; unsigned int xx = x * 1000; // xx == 32453, since want keep 3 decimals 

if convert manually 32453 binary format: 0b 0111 1110 1100 0101 or 0x7ec5

so, have array of unsigned chars:

unsigned char parsednumber [2]; parsednumber[0] = 0x7e; parsednumber[1] = 0xc5; 

so far have:

float number = 32.453 unsigned int numberuint = number * 1000;  unsigned char parsednumber [2]; parsednumber[0] = (numberuint << 8) >> 8; parsednumber[1] = numberuint >> 8; cout << parsednumber << endl; 

i try use left shift , right shift select upper , lower part of numberint, right in parsednumber gibberish...

unsigned char parsednumber [2]; parsednumber[0] = (numberuint << 8) >> 8; parsednumber[1] = numberuint >> 8; 

the assignment parsednumber[0] not need. you're shifting 8 bits left, undoing 8 bit right shift. might clear upper bits, or might not.

instead, consider (assuming least significant byte first):

unsigned char parsednumber [2]; parsednumber[0] = numberuint & 0xff; parsednumber[1] = (numberuint >> 8) & 0xff; 

here explicitly mask out bits we're not interested in each byte.

when print result, keep in mind it's not null-terminated string, , may contain non-printable characters.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -