C 语言常用运算符

1.数学运算符

#include <iostream>
#include <math.h>
#define M_PI 3.14159265

int main() {
    int32_t a = (10 + 2 - 8) * 9 / 3;
    printf("%d\n", a);

    printf("%f\n",sin(M_PI));
    return 0;
}


2.逻辑运算符

#include <stdint.h>
#include <stdio.h>

//    && 与  ||或 !非

#define MALE 1
#define FEMALE 2

int main() {

    int32_t score = 80;
    if (score >= 60 &&
        score <= 100) {
        printf("OK\n");
    } else {
        printf("Fail or invalid score\n");
    }

    if (score < 60 ||
        score > 100) {
        printf("Fail or invalid score\n");
    } else {
        printf("OK\n");
    }

    int sex = MALE;
    if (sex != FEMALE) {
        printf("The person is male\n");
    } else {
        printf("The person is female\n");
    }
    return 0;
}


3.位运算

#include <stdio.h>
#include <stdint-gcc.h>

/**
 * & 位与
 * | 位或
 * ~ 位反
 * ^ 异或
 * >> 右移
 * << 左移
 */
int main() {

    int a = 0b01;
    int b = 0b10;


    printf("位与:%d\n", a & b);
    printf("位或:%d\n", a | b);
    printf("异或:%d\n", a ^ b);

    uint8_t c = 1;//0b00000001 求反 0b11111110
    printf("%d\n", c);
    c = ~c;
    printf("位反:%d\n", c);

    uint8_t d = 0b11111110;
    printf("%d\n", d);

    int8_t e = 1;//-128...-3,-2,-1,  中心   0,1,2.....-127
    e = ~e;
    printf("位反:%d\n", e);

    int f = 8;
    printf("右移:%d\n", f >> 1);

    //提取颜色通道
    uint32_t color = 0xFFFEFAFB;//ARGB(Alpha,Red,Green,Blue)
    uint32_t tmp = color & 0x00FF0000;//0b11111110 & 0b11111111 = 0b11111110
    // tmp  0x00000000 11111110 00000000 00000000
    uint8_t red = tmp >> 16;
    printf("%d\n",red);

    return 0;
}


 

posted @ 2016-12-20 02:06  changchou  阅读(429)  评论(0编辑  收藏  举报