Language/C
[따배씨] 15.5 2의 보수 표현법 확인해보기
migrationArc
2021. 7. 23. 18:57
따배씨 - 따라하며 배우는 C언어
15강 비트 다루기
15.5 2의 보수 2's Complement 표현법 확인해보기
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void print_binary(const char num);
int main()
{
/*
Signed Integers
- Sign-magnitude representation
00000001 is 1 and 10000001 is -1
00000000 is +0, 10000000 is -0
Two zeros +0, -0, from -127 to +127
- One's complement method
To reverse the sign, invert each bit.
00000001 is 1 and 11111110 is -1.
11111111 is -0
from -127 to +127
*/
print_binary(127);
// Decimal 127 == Bianry 01111111
print_binary(-127);
// Decimal -127 == Bianry 10000001
print_binary(~127 + 1);
// Decimal -127 == Bianry 10000001
print_binary(12);
// Decimal 12 == Bianry 00001100
print_binary(-12);
// Decimal -12 == Bianry 11110100
print_binary(~12 + 1);
// Decimal -12 == Bianry 11110100
return 0;
}
void print_binary(const char num)
{
printf("Decimal %3d \t== Bianry ", num);
const size_t bits = sizeof(num) * 8;
for (size_t i = 0; i < bits; i++)
{
const char mask = (char)pow((double)2, (double)(bits - 1 - i));
if ((num & mask) == mask)
printf("%d", 1);
else
printf("%d", 0);
}
printf("\n");
}