简体   繁体   English

在C中将int拆分为char数组

[英]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.我有一个 int,我需要将它拆分为一个字符数组,因此每个数组位置有 2 个字符。 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.将您正在执行按位运算的变量更改为unsigned ,并在分配给数组之前屏蔽移位结果。 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;您也不应该将sizeof(length)除以 2。它适用于仅使用数字的低位一半的值,但不适用于较大的值; eg if you use length = 1096800;例如,如果您使用length = 1096800; the result will be 48824 .结果将是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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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