Store an int in a char array?

后端 未结 10 1579
攒了一身酷
攒了一身酷 2020-11-27 17:24

I want to store a 4-byte int in a char array... such that the first 4 locations of the char array are the 4 bytes of the int.

Then, I want to pull the int back out o

相关标签:
10条回答
  • 2020-11-27 17:32

    Not the most optimal way, but is endian safe.

    
    int har = 0x01010101;
    char a[4];
    a[0] = har & 0xff;
    a[1] = (har>>8)  & 0xff;
    a[2] = (har>>16) & 0xff;
    a[3] = (har>>24) & 0xff;
    
    0 讨论(0)
  • 2020-11-27 17:33
    union value {
       int i;
       char bytes[sizof(int)];
    };
    
    value v;
    v.i = 2;
    
    char* bytes = v.bytes;
    
    0 讨论(0)
  • 2020-11-27 17:35
    #include <stdio.h>
    
    int main(void) {
        char a[sizeof(int)];
        *((int *) a) = 0x01010101;
        printf("%d\n", *((int *) a));
        return 0;
    }
    

    Keep in mind:

    A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined.

    0 讨论(0)
  • 2020-11-27 17:48
    char a[10];
    int i=9;
    
    a=boost::lexical_cast<char>(i)
    

    found this is the best way to convert char into int and vice-versa.

    alternative to boost::lexical_cast is sprintf.

    char temp[5];
    temp[0]="h"
    temp[1]="e"
    temp[2]="l"
    temp[3]="l"
    temp[5]='\0'
    sprintf(temp+4,%d",9)
    cout<<temp;
    

    output would be :hell9

    0 讨论(0)
  • 2020-11-27 17:49

    Don't use unions, Pavel clarifies:

    It's U.B., because C++ prohibits accessing any union member other than the last one that was written to. In particular, the compiler is free to optimize away the assignment to int member out completely with the code above, since its value is not subsequently used (it only sees the subsequent read for the char[4] member, and has no obligation to provide any meaningful value there). In practice, g++ in particular is known for pulling such tricks, so this isn't just theory. On the other hand, using static_cast<void*> followed by static_cast<char*> is guaranteed to work.

    – Pavel Minaev

    0 讨论(0)
  • 2020-11-27 17:49

    You can also use placement new for this:

    void foo (int i) {
      char * c = new (&i) char[sizeof(i)];
    }
    
    0 讨论(0)
提交回复
热议问题