This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

converting types

hi Forum,

how can i convert items in a Array from typ Char[] in an Integer-Type?

example:
char data[] = "110111";
int sum = 0;

sum = (int)data;

or should i sum the all items in the array bitwise?

  • I'm assuming you are converting a binary number stored as a string into int. This should do the job:

    char data[] = "110111";
    int sum = 0;
    
    int i;
    for (i=0; data[i] != '\0'; i++) {
        sum <<= 1;
        if ( data[i] == '1' )
            sum |= 1;
    }
    /* it's done */
    
    Or, if you wanted to count the number of ones in the string:
    char data[] = "110111";
    int sum = 0;
    
    int i;
    for (i=0; data[i] != '\0'; i++) {
        sum += data - '0';
    }
    /* it's done */
    
    No offense, but with questions like these how do you expect to write any program in C? There are lots of good books on C, say K&R.

    - mike

  • You seem to have a fundamental misunderstanding about what an array is.

    In 'C', an array's name gives the address of the 1st element of the array - it is effectively a pointer to the start of the array.

    sum = (int)data;
    attempts to take the pointer value, and put it into an int variable.
    This has absolutely nothing whatsoever to do with the values of the elements of the array!

    If you want to find the sum of all the elements in an array, you will have to add them all up:
    sum = array[0] + array[1] + array[2] etc, etc,...
    Of course, in real life, you'd probably use a loop to do this.

    An array definition like
    char array[] = "110111";
    initialises the elements as:

    array[0] = '1'
    array[1] = '1'
    array[2] = '0'
    array[3] = '1'
    array[4] = '1'
    array[5] = '1'
    array[6] = 0x00

    Note the 1st six elements contain the characters '0' and '1' (ASCII code values 0x30 and 0x31) - they do not have numerical values zero and one.

    Note also that data is a reserved keyword in C51.