简体   繁体   中英

Split int into char array in C

I have an int, and I need to split it to a char array, so 2 chars in each array position. After that, I need to do the opposite process. This is the best I could come up with, but I still couldn't make it work. Any suggestions?

#include <stdio.h>
#include <stdlib.h> 
int main()
{
    int length = 10968;
    int bytesNeeded = sizeof(length) / 2;
    char *controlPacket = (char*)malloc(sizeof(char*)*bytesNeeded);
    for (int i = 0; i < bytesNeeded; i++)
    {
        controlPacket[i] = (length >> (8* i));
    }
    int newSize = 0;
    for (int i = 0; i < bytesNeeded; i++)
    {
        newSize += (controlPacket[i] << (8 * i));
    }
    printf("Newsize is: %d\n", newSize);
}

Change the variables that you're performing bitwise operations on to unsigned , and also mask the result of shifting before assigning to the array. Otherwise, you get overflow, which causes incorrect results (maybe undefined behavior, I'm not sure).

You also shouldn't divide sizeof(length) by 2. It will work for values that only use the low order half of the number, but not for larger values; eg if you use length = 1096800; the result will be 48824 .

#include <stdio.h>
#include <stdlib.h> 
int main()
{
    unsigned int length = 10968;
    int bytesNeeded = sizeof(length);
    unsigned char *controlPacket = malloc(sizeof(unsigned char)*bytesNeeded);
    for (int i = 0; i < bytesNeeded; i++)
    {
        controlPacket[i] = (length >> (8* i) & 0xff);
    }
    unsigned int newSize = 0;
    for (int i = 0; i < bytesNeeded; i++)
    {
        newSize += (controlPacket[i] << (8 * i));
    }
    printf("Newsize is: %d\n", newSize);
    free(controlPacket);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM