Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid trap representation with memcpy

Tags:

c

memcpy

Please consider the following code:

float float_value = x; // x is any valid float value
int int_value = 0;
size_t size = sizeof(int) < sizeof(float) ? sizeof(int) : sizeof(float);
memcpy(&int_value, &float_value, size);

As far as i know this could result in an trap representation. My questions:

  1. Is that true?
  2. If not, why?
  3. If not, is there another way avoiding a possible trap representation?
like image 688
Johannes Avatar asked Dec 15 '11 22:12

Johannes


1 Answers

The sanctioned way which won't produce any trap representation is

unsigned char obj[sizeof float];
memcpy(obj, &float_value, sizeof float);

Then you can use the bytes of the object representation to build your desired int.

But using fixed-width integers as mentioned by Stephen Canon is better - unless you have a weird float size.

like image 186
Daniel Fischer Avatar answered Oct 27 '22 09:10

Daniel Fischer