get int value from array of char in c language

c

Solution

Instead of left shifting with `<<` operator (which is more or less equivalent to multiplying by `2^N`), you should rather multiply by `10^N`. Here is how you can do:

int year = bytes[0] * 1000 +
           bytes[1] * 100 +
           bytes[2] * 10 +
           bytes[3];

int month = bytes[4] * 10 +
            bytes[5];

int day = bytes[6] * 10 +
          bytes[7];

Of course, you can use loops to make your code more readable (if necessary).

enum {
   NB_DIGITS_YEAR = 4,
   NB_DIGITS_MONTH = 2,
   NB_DIGITS_DAY = 2,
   DATE_SIZE = NB_DIGITS_YEAR + NB_DIGITS_MONTH + NB_DIGITS_DAY
};

struct Date {
   int year, month, day;
};

int getDateElement(char *bytes, int offset, int size) {
   int power = 1;
   int element = 0;
   int i;

   for (i = size - 1; i >= 0; i--) {
      element += bytes[i + offset] * power;
      power *= 10;
   }

   return element;
}

struct Date getDate(char *bytes) {
   struct Date result;
   result.year = getDateElement(bytes, 0, NB_DIGITS_YEAR);
   result.month = getDateElement(bytes, NB_DIGITS_YEAR, NB_DIGITS_MONTH);
   result.day = getDateElement(bytes, NB_DIGITS_YEAR + NB_DIGITS_MONTH, NB_DIGITS_DAY);
   return result;
}

With this last code it is easier to change the format of the date stored in `bytes`.

Example:

int main(void) {
   char bytes[DATE_SIZE] = {2, 0, 1, 3, 0, 8, 1, 9};
   struct Date result = getDate(bytes);
   printf("%02d/%02d/%04d\n", result.day, result.month, result.year);
   return 0;
}

Output:

19/08/2013

Problem

I have an array of characters like: ``` char bytes[8]={2,0,1,3,0,8,1,9} ``` I want to take the first four chars from this array below, and put them into a new integer variable. How can I do this? I am trying to shift them, but this logic is not working. Any idea? Thanks. Example: from this array to get: year month day ``` char bytes[8]={2,0,1,3,0,8,1,9} int year = 2013 ...... month = 8 ............ day = 19 ```

Original source

Related problems