C ++. reinterpret_cast from double to unsigned char *

Today I had a little game with C ++, and it seemed strange to me, but, most likely, due to a misunderstanding and lack of clean C code recently.

What I was looking for was originally converting double to an array of unsigned chars. I realized that 64 bits of double (sizeof (double) is 8) will now be represented as 8 8-bit characters. For this, I used reinterpret_cast.

So, here is some code to convert from double to char array, or at least I thought it was doing. The problem is that it was returning 15 from strlen instead of 8, why am I not sure.

double d = 0.3;

unsigned char *c = reinterpret_cast<unsigned char*> ( &d );

std::cout << strlen( (char*)c ) << std::endl;

So the first one was my problem. But then I tried the following and found that he returned 11, 19, 27, 35. The difference between these numbers is 8, so something correct happens at some level. But why does this not return 15, 15, 15, 15, (since it returned 15 in the above code).

double d = 0.3;
double d1 = 0.3;
double d2 = 0.3;
double d3 = 0.3;

unsigned char *c_d = reinterpret_cast<unsigned char*> ( &d );
unsigned char *c_d1 = reinterpret_cast<unsigned char*> ( &d1 );
unsigned char *c_d2 = reinterpret_cast<unsigned char*> ( &d2 );
unsigned char *c_d3 = reinterpret_cast<unsigned char*> ( &d3 );

std::cout << strlen( (char*)c_d ) << std::endl;
std::cout << strlen( (char*)c_d1 ) << std::endl;
std::cout << strlen( (char*)c_d2 ) << std::endl;
std::cout << strlen( (char*)c_d3 ) << std::endl;

So, I looked at the addresses of the characters, and they are.

0x28fec4
0x28fec0
0x28febc
0x28feb8 

Now it makes sense, considering that the size of the unsigned char * on my system is 4 bytes, but I thought that the correct amount of memory would be allocated from the cast, otherwise it seems like reinterpret_cast is a rather dangerous thing ... Also, if I do

for (int i = 0; i < 4; ++i) {
    double d = 0.3;

    unsigned char *c = reinterpret_cast<unsigned char*> ( &d );

    std::cout << strlen( (char*)c ) << std::endl;
}

Fingerprints 11, 11, 11, 11!

, , , , , , ( ). ++, , raw char , .

, , .

15? 4 ? 11, 11, 11, 11?

.

+5
3

strlen , const char*, char 0. - , , , double, . strlen double, 0.

"Hello". , ASCII, ( ):

48 65 6c 6c 6f 00

strlen , 0 , .

IEEE 754 0.3:

3F D3 33 33 33 33 33 33

, 0 , strlen , .

, , , , , 0 , undefined, .

+11

strlen( (char*)c ), strlen .

, - "" 8- 9- , 8 double.

, char*. .

+6

:

  • sizeof(double), , 4. 8. .
  • The pointer reinterpret_cast<unsigned char*>(&d)does not point to a string with a null character. strlenworks by iterating until it finds zero. You are there in undefined.
+2
source

All Articles