Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /// https://codeforwin.org/2015/08/c-program-to-find-twos-complement-of-binary-number.html
- #include <stdlib.h>
- #define SIZE 8
- int main()
- {
- char binary[SIZE + 1];
- char U1[SIZE + 1];
- char U2[SIZE + 1];
- int i, carry=1;
- printf("Wpisz %d bit liczbe w systemie binarnym: ", SIZE);
- /// wpisz ciag 8 bitow
- gets(binary);
- /// zamiana na U1
- for(i=0; i<SIZE; i++)
- {
- if(binary[i] == '1')
- U1[i] = '0';
- else if(binary[i] == '0')
- U1[i] = '1';
- }
- U1[SIZE] = '\0';
- ///U2 = Dodaj 1 do U1
- for(i=SIZE-1; i>=0; i--)
- {
- if(U1[i] == '1' && carry == 1)
- {
- U2[i] = '0';
- }
- else if(U1[i] == '0' && carry == 1)
- {
- U2[i] = '1';
- carry = 0;
- }
- else
- {
- U2[i] = U1[i];
- }
- }
- U2[SIZE] = '\0';
- printf("Binarny = %s\n", binary);
- printf("U1 = %s\n", U1);
- printf("U2 = %s\n", U2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement