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?

Parents
  • 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

Reply
  • 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

Children
No data