-1

I was trying to convert a c++ struct variable to a byte array. But unfortunately, I am getting a weird output.

Code:

#include <bits/stdc++.h>

using namespace std;

struct A{
    int  x; 
};

int main ()
{
    A obj;
    obj.x = 892323;

    char *x =(char *)malloc(sizeof(obj));
    memcpy(x, (unsigned char *)&obj, sizeof(obj));

    for(int i=0; i < sizeof(obj); i++)
        printf("%02X\n",x[i]);
    
    return 0;
}

output:

FFFFFFA3
FFFFFF9D
0D
00

Can anyone tell me why I am getting this kind out output?

mahbubcseju
  • 2,200
  • 2
  • 16
  • 21

1 Answers1

0

The output is correct, even if not be what you would expect. The underlying cause is that it is implementation defined whether the char type is signed or unsigned. In your platform, it is signed so the byte 0xA3 is -93. When you pass it to the printf function it is promoted to an int. But the %x modifier will convert it to an unsigned value by adding 0x100000000 when int (and unsigned int) use 32 bits to give 4294967203 or 0xffffffa3.

If you want to get only 2 character per byte, you should use unsigned char. With

...
unsigned char* x = (unsigned char*)malloc(sizeof(obj));
...

You would get:

A3
9D
0D
00

which is indeed the byte representation of 892323 or 0xd9da3 on a little endian system with 32 bits integers.

BTW, your code heavily uses the C standard library. While it is not wrong because the C++ standard explicitely includes it in the C++ standard library there are 2 weak points:

  • your code cannot benefit of all the type safety provided by the C++ language and its library
  • you will fail to learn how to use modern C++
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252