如何将两个或三个字符组合成一个整数/字符

时间:2014-04-14 10:27:52

标签: c algorithm encoding

我从UART获取字符,例如“\ n43 \ n”或“\ n912 \ n”。我打算将它作为一个整数,以便比较我的应用程序中的值。

示例:

     int a = 43;
     int b;
     /*Combine the character getting from the uart copy to integer "b";*/
     if(a==b)
     {
         /*perform some operation*/
     }

2 个答案:

答案 0 :(得分:1)

您可以安全地执行以下操作,因为字符ASCII小于256

int combine(char a, char b, char c)
{
    return (a << 20) | (b << 10) | c;
}

当a,b,c的值小于1000时,这适用于2^10 = 1024

让他们回来:

a = combined >> 20;
b = (combined >> 10) & 0x3ff;
c = combined & 0x3ff;

答案 1 :(得分:0)

#include<string.h>
#include<stdio.h>
int main()
{
int number;
char a[30] = "\n43\n";
number = atoi(a);
printf("magic is %d",number);
if(number == 43)
   printf("This works....!\n");
return 0;
}

你有没有听过atoi()

修改

int main()
{
int number = 0;
char a[30];
a[0] = '4';
a[1] = '3';
a[2] = '\0';
number = atoi(a);
printf("magic is %d",number);
return 0;
}