Код с лекции 2:
#include <stdio.h>
// магическая функция, которая печатает биты.
void printBits(size_t const size, void const * const ptr) {
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
}
puts("");
}
void unsigned_overflow() {
printf("unsigned_overflow\\n");
unsigned char a = 200;
unsigned char b = 128;
unsigned char c = a + b;
printf("a=%d b=%d a+b=%d\\n", a, b, c);
printBits(sizeof(a), &a);
printBits(sizeof(b), &b);
printBits(sizeof(c), &c);
}
void sign() {
printf("sign\\n");
unsigned char a = 249;
unsigned char b = 7;
printf("a=%d\\t", a);
printBits(sizeof(a), &a);
printf("a=%d\\n", (char)a);
printf("b=%d\\t", b);
printBits(sizeof(b), &b);
printf("signed a+b = %d\\n", (char)a+(char)b);
printf("unsigned a+b = %d\\n", a+b);
}
void assign_overflow() {
printf("assign_overflow\\n");
short a = 642;
printBits(sizeof(a), &a);
char b = a;
printf("--------");
printBits(sizeof(b), &b);
printf("a=%d b=%d\\n", a,b);
}
void assign_overflow2() {
printf("assign_overflow2\\n");
short a = 632;
printBits(sizeof(a), &a);
char b = a;
printf("--------");
printBits(sizeof(b), &b);
printf("a=%d b=%d\\n", a,b);
}
void float_repr() {
printf("float_repr\\n");
{
float a = 0.5;
printf("a=%f\\n", a);
printBits(sizeof(a), &a);
}
{
float a = 0.5+0.25;
printf("a=%f\\n", a);
printBits(sizeof(a), &a);
}
{
float a = 0.5+0.125;
printf("a=%f\\n", a);
printBits(sizeof(a), &a);
}
{
float a = 16;
printf("a=%f\\n", a);
printBits(sizeof(a), &a);
}
{
float a = -248.75;
printf("a=%f\\n", a);
printBits(sizeof(a), &a);
}
}
void float_precision() {
// <https://floating-point-gui.de/errors/comparison/>
printf("float_precision\\n");
float f = 0.1f;
float sum = 0;
for (int i = 0; i < 10; ++i) {
sum += f;
}
float product = f * 10;
printf("sum = %1.15f, mul = %1.15f\\n", sum, product);
printf("sum eq %d\\n", sum == product);
}
void float_precision2() {
printf("float_precision2\\n");
float a = 5.2;
float b = 3.0;
float c = 15.6;
printf("a=%f c=%f a*3=%f eq=%d\\n",a,c,a*b,a*b == c);
}
int main(void) {
unsigned_overflow();
sign();
assign_overflow();
assign_overflow2();
float_repr();
float_precision();
float_precision2();
}
Вывод программы при запуске:
unsigned_overflow
a=200 b=128 a+b=72
11001000
10000000
01001000
sign
a=249 11111001
a=-7
b=7 00000111
signed a+b = 0
unsigned a+b = 256
assign_overflow
0000001010000010
--------10000010
a=642 b=-126
assign_overflow2
0000001001111000
--------01111000
a=632 b=120
float_repr
a=0.500000
00111111000000000000000000000000
a=0.750000
00111111010000000000000000000000
a=0.625000
00111111001000000000000000000000
a=16.000000
01000001100000000000000000000000
a=-248.750000
11000011011110001100000000000000
float_precision
sum = 1.000000119209290, mul = 1.000000000000000
sum eq 0
float_precision2
a=5.200000 c=15.600000 a*3=15.599999 eq=0