Mostrando entradas con la etiqueta Three Little Endians. Mostrar todas las entradas
Mostrando entradas con la etiqueta Three Little Endians. Mostrar todas las entradas

lunes, 24 de octubre de 2011

One Little, Two Little, Three Little Endians , uva

#include<iostream>
#include<bitset>
#include<cstdio>
#include<vector>
#include<cmath>
#define db(a) cout << #a << " = " << a << endl;
using namespace std;
string complemento2(string cad){
	for(int i = 0; i < 32; i++) 
		cad[i] = cad[i] == '1' ? '0' : '1';
	bool carry = true;
	for(int i = 31; i >= 0 && carry; i--){
		if(cad[i] == '0') {
			if(carry)
				cad[i] = '1', carry = false;
		}
		else
			if(carry) cad[i] = '0';	
	}
	return cad;
}
int to_int(string cad){
	int factor = 1;
	if(cad[0] == '1')
	cad = complemento2(cad), factor *= -1;
	int num = 0;
	for(int i = 0; i < 32; i++){
		if(cad[i] == '1')
		num += pow(2., 31 - i);
	}
	return factor * num;
}
int main(){
	int n;
	while(scanf("%d", &n) != EOF){
		bitset<32> bit_set = n;
		string num_b = bit_set.to_string();
		string concat = "", res = "";
		for(int i = 1; i <= 32; i++)
			if (i % 8 != 0) concat += num_b[i - 1];
			else concat += num_b[i - 1], res = concat + res, concat = "";
		int rpta = to_int(res);
		printf("%d converts to %d\n", n, rpta);
	}
	return 0;
}