user2598064
user2598064

Reputation: 157

Copying Ascii Value to int

I have code snippet as Below

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;
}

Can anybody help me in solving this. consider i have an ascii value abcd stored in an array t[]. I want to store the same value in 'm'. m is my unsigned int variable . which stores the major number. when i copy the array into m & print m . m should print abcd. can anybody state their logic.

Upvotes: 2

Views: 516

Answers (3)

David Heffernan
David Heffernan

Reputation: 613311

As I understand you, you want to encode the 4 characters into a single int.

Your bit shifting is not correct. You need to shift by 8 bits rather than 2. You also need to perform the shifting before the bitwise or. Otherwise you shift too far.

And it makes more sense, in my view, to print the character rather than 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;
}

Upvotes: 4

Petr Skocik
Petr Skocik

Reputation: 60107

Why not just look at the t array as an unsigned int?:

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

Or you could use an union for nice access to the same memory block in two different ways, which I think is better than shifting bits manually.

Below is an union example. With unions, both the t char array and the unsigned int are stored in the same memory blob. You get a nice interface to each, and it lets the compiler do the bit shifting (more portable, I guess):

    #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;
}

Upvotes: 2

haccks
haccks

Reputation: 106092

Simply assign t[p] to m.

m = t[p];  

this will implicitly promote char to 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);
}

Upvotes: 0

Related Questions