/* * examples.c */ #include #include int main(int argc, char *argv[]) { int32_t a, b, c; uint32_t x, y, z; /* we can use either integer representation or hex representation as * literals */ a = -1234567890; b = 0x3ade68b1; c = 42; x = 1234567890; y = 0xffffffff; z = 9; printf("Integer values:\n"); printf("a has value %d\n", a); printf("b has value %d\n", b); printf("c has value %d\n", c); printf("\n"); printf("x has value %d\n", x); printf("y has value %d\n", y); printf("z has value %d\n", z); printf("\n"); printf("Integer arithmetic:\n"); /* we can add */ int32_t sum; sum = a + b; printf("a + b is %d\n", sum); /* we can subtract */ int32_t diff; diff = y - x; printf("y - x is %d\n", diff); /* we can multiply */ int32_t product; product = c * z; printf("c * z is %d\n", product); /* we can divide... but when the operands are integers, the result is just * the integer portion---no fraction */ int32_t quotient; quotient = c / z; printf("c / z is %d\n", quotient); /* we can, however, get the remainder using the "%" operator, which is * pronounced "mod"; note how we need "%%" in our string to print a * literal percent symbol, so printf doesn't think it's a format specifier */ int32_t remainder; remainder = c % z; printf("c %% z is %d\n", remainder); printf("\n"); printf("Bitwise operations:\n"); /* we can perform bitwise inversion */ int32_t inverted; inverted = ~b; printf("~b is %d, which is 0x%08x in hex\n", inverted, inverted); /* we can perform bitwise or */ int32_t orred; orred = a | b; printf("a | b is 0x%08x\n", orred); /* bitwise and */ int32_t anded; anded = a & b; printf("a & b is 0x%08x\n", anded); /* and bitwise xor */ int32_t xored; xored = a ^ b; printf("a ^ b is 0x%08x\n", xored); printf("\n"); printf("String stuff:\n"); /* one way to think of a string is as an array of characters, though if we * want to assign a literal value to it, we MUST do so when we declare the * string; when initialized in this way, we must explicitly include the * null byte ('\0') after all the characters so that C knows where it ends */ char s[50] = "hello world\0"; /* if we want to print a string but we don't need any formatting (like the * %d stuff above), we can use the puts function, which will also add a * newline at the end */ puts(s); /* we can modify the string by changing items in the array (note that * since items in the array are characters, and the code below modifies * individual characters, the character is enclosed in single quotes */ s[0] = 'j'; puts(s); /* as suggested in class, C can treat characters like integers: we can do * arithmetic on them! */ s[0] = s[0] - 32; s[6] = s[6] - 32; puts(s); }