Числа A,B,C хранятся в unsigned long X в виде:
<- 12 бит-> <- 10 бит-> <- 10 бит->
<- c -> <- b -> <- a ->
<- x ->
Найти значение суммы a + b + c, выполнив операцию сложения «в столбец». Почему не работает функция binadd?
//подключаемые файлы с прототипами функций
#include<iostream>
#include <stdio.h>// ввода-вывода
#include <string.h>//работы со строками
#include <windows.h> //WinAPI
//прототипы функций
using namespace std;
void BinOut(unsigned char);
unsigned long BinAdd(unsigned long, unsigned long, unsigned long);
//глобальные переменные
unsigned long a, b, c, sum, x;
void main()
{
cin >> x;
for (int i = 0; i < 32; i++)
{
if (0 <= i && i < 12)
{
c=c << 1;
c |= ((x >> (31-i)) & 1);
cout << ((x >> (31-i)) & 1);
}
else if (12 <= i && i < 22)
{
b= b << 1;
b = b | ((x >> (31-i)) & 1);
cout << ((x >> (31 - i)) & 1);
}
else
{
a=a << 1;
a =a | ((x >> (31-i)) & 1);
cout << ((x >> (31 - i)) & 1);
}
}
cout <<endl <<"a=" <<a << endl;
BinOut(a);
cout <<"b="<< b << endl;
BinOut(b);
cout <<"c="<< c<< endl;
BinOut(c);
sum = a + b + c;
cout << "sum=" << sum << endl;
sum = BinAdd(a, b, c);
cout << "sum=" << sum << endl;
system("pause");
}
void BinOut(unsigned char x)
{ int i;
printf("Binary presentation: ");
for (int i = 0; i < 10; i++) {
int m = (x >> (9 - i)) & 1; //output in binary number
cout << m;
}
cout << endl;
}
unsigned long BinAdd(unsigned long x, unsigned long y, unsigned long z)
{
int i;
unsigned long mem = 0, rez = 0;
for (i = 0; i<10; i++) {
rez >> 1;
if ((((z >> (9-i)) & 1)) ^ (((x >> (9-i)) & 1))^ (((y >> (9-i)) & 1))) { if (!(mem & 1)) rez |= 0x80; }
else if (((x >> (9-i)) & 1)) if (mem) { mem = 1; rez |= 0x80; }
else mem = 1;
else
if (mem) { mem = 0; rez |= 0x80; }
}
return rez;
};
Ошибка номер раз
void BinOut(unsigned char x)
Сюда влезет только 8 бит.
Я стесняюсь спросить, а почему нельзя сделать так?
struct test {
unsigned short a : 12;
unsigned short b : 10:
unsigned short c : 10;
};
test t;
cout << t.a + t.b + t.c
Или вот "в столбец"
unsigned long add(unsigned long a, unsigned long b) {
unsigned long res = 0;
char cf = 0;
char pos = 0;
while (!a || !b || !cf) {
char t = (a & 1) + (b & 1) + cf;
cf = t >> 1;
t = t & 1;
res = (t << pos) | res;
pos++;
a = a >> 1;
b = b >> 1;
}
return res;
}
unsigned long x, a, b, c;
cin >> x;
a = x & 0xFFF;
x = x >> 12
b = x & 0x3FF;
x = x >> 10;
c = x & 0x3FF;
unsigned long sum;
sum = add(add(a, b), c);
cout << sum;
Сборка персонального компьютера от Artline: умный выбор для современных пользователей