将Ascii值复制到int

时间:2014-02-05 13:09:06

标签: c ascii

我的代码段如下

unsigned char p = 0;
unsigned char t[4] = {'a','b','c','d'};     
unsigned int m = 0;
for(p=0;p<4;p++)
{
m |= t[p];
printf("%c",m);
m = m << 2;
}

任何人都可以帮我解决这个问题。考虑我有一个存储在数组abcd中的ascii值t[]。我想在'm'中存储相同的值。 m是我的unsigned int变量。它存储了主要数字。当我将数组复制到m&amp;打印m。 m应打印abcd。谁能说出自己的逻辑呢?

3 个答案:

答案 0 :(得分:4)

据我了解,您希望将4个字符编码为单个int。

您的位移不正确。您需要移位8位而不是2位。您还需要在按位或之前执行移位。否则你转移太远了。

在我看来,更有意义的是打印角色而不是m

#include <stdio.h>

int main(void)
{
    const unsigned char t[4] = {'a','b','c','d'};     
    unsigned int m = 0;
    for(int p=0;p<4;p++)
    {
        m = (m << 8) | t[p];
        printf("%c", t[p]);
    }
    printf("\n%x", m);
    return 0;
}

答案 1 :(得分:2)

为什么不将t数组视为unsigned int?:

  unsigned int m = *(unsigned int*)t;

或者您可以使用联合以两种不同的方式很好地访问相同的内存块,我认为这比手动移位更好。

下面是一个联合示例。对于联合,t char数组和unsigned int都存储在同一个内存blob中。你得到一个很好的接口,它让编译器进行位移(我想更便携):

    #include <stdio.h>

typedef union {
  unsigned char t[4];
  unsigned int m;
} blob;


int main()
{
  blob b;
  b.t[0]='a';
  b.t[1]='b';
  b.t[2]='c';
  b.t[3]='d';
  unsigned int m=b.m; /* m holds the value of blob b */
  printf("%u\n",m);   /* this is the t array looked at as if it were an unsignd int */
  unsigned int n=m;   /* copy the unsigned int to another one  */
  blob c;             
  c.m=n;              /* copy that to a different blob */ 
  int i;
  for(i=0;i<4;i++)
    printf("%c\n",c.t[i]);   /* even after copying it as an int, you can still look at it as a char array, if you put it into the blob union -- no manual bit manipulation*/

  printf("%lu\n", sizeof(c));   /* the blob has the bytesize of an int */
  return 0;
}

答案 2 :(得分:0)

只需将t[p]分配给m即可。

m = t[p];  

这会隐式地将char提升为unsigned int

unsigned char p = 0;
unsigned char t[4] = {'a','b','c','d'};     
unsigned int m = 0;
for(p=0;p<4;p++)
{
    m = t[p];
    printf("%c",m);
}