-1

I just want to combine 4 characters into one unsigned long variable as shown below.

char y[16];
unsigned long Timer ;

y[12] = '1' ;
y[13] = '0' ;
y[14] = '1' ;
y[15] = '1' ; 
Timer  =   y[15] - '0' ;
Timer |=  (unsigned long) (y[12] - '0' << 24);
Timer |=  (unsigned long) (y[13] - '0'  << 16);
Timer |=  (unsigned long) (y[14] - '0'  << 8);

printf("%lu" , Timer);

I want the Timer to equal 1011 but I keep getting 1 as the output.

Ammar
  • 1,203
  • 5
  • 27
  • 64
  • there is a problem with where the parens are located. the values of y[] are bytes, so shifting a byte 8 or more bits left results in 0. suggest '(unsigned long)(y[12] - '0') << 24;' and similar for the next two lines. – user3629249 Dec 30 '14 at 21:39
  • It bears asking, what type of processor/compiler are you using. Specifically, is an unsigned long 32 bits? Is that also the word size? What is the endianness? Some answers to this question which use shift operations might not be portable to another processor that doesn't have the same endianness. EDIT: I see your tag MPLAB, so I assume you are using a PIC, correct? If so, 16 bit or 32? – Nick Dec 30 '14 at 21:40
  • I'm using PIC18 but the question was answered already below. – Ammar Dec 30 '14 at 21:44

1 Answers1

3

This should work for you:

(You just need to know the tricks)

#include <stdio.h>

int main() {

    char y[16];
    unsigned long Timer ;

    y[12] = '1';
    y[13] = '0';
    y[14] = '1';
    y[15] = '1';

    Timer = y[12] - '0';  //- '0' To get the digit, here 1, and this for every digit
    Timer = (Timer * 10) + y[13] - '0';  //*10 to make place for the next digit, and this for every digit (expect the 1st one)
    Timer = (Timer * 10) + y[14] - '0';
    Timer = (Timer * 10) + y[15] - '0';

    printf("%lu" , Timer);

    return 0;

}

Output:

1011
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 2
    Can you add some explanation, a code only answer with the line "This should work for you:" is not very helpful. Explanation for those "tricks" is what OP is looking for, not code which he can copy/paste. – 2501 Dec 30 '14 at 20:09