首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎样将二进制补码转化为原码?该如何处理

2012-04-27 
怎样将二进制补码转化为原码?如,怎样将二进制补码1000001111000011010010010,000010101111000010101111000

怎样将二进制补码转化为原码?
如,怎样将二进制补码1000001111000011010010010,0000101011110000101011110001010,101010111110101010001,01010100001111等化为原码的形式?
有现成的函数能直接转换吗?

[解决办法]

C/C++ code
#include<climits>#include<string>#include<iostream>#include<bitset>using namespace std;#define BINARY_BIT (20)#define BINARY_SIGN (1<<(BINARY_BIT-1))#define BINARY_MASK (~-(1<<BINARY_BIT))string true_form_long(const string& complement){    bitset<sizeof(long)*8> bits(complement);    unsigned long val = bits.to_ulong();    if(val > (unsigned long)(BINARY_SIGN-1))    {        val=(val&(BINARY_SIGN-1));        return bitset<sizeof(long)*8>(((~val+1)|BINARY_SIGN)&BINARY_MASK).to_string().substr(32-BINARY_BIT);    }    if(complement.size()<BINARY_BIT)    {        string s(BINARY_BIT-complement.size(),'0');        return s+complement;    }    return complement;}string not_code(const string & complement){    bitset<sizeof(long)*8> bits(complement);    unsigned long val = bits.to_ulong();    return bitset<sizeof(long)*8>((~val)&BINARY_MASK).to_string().substr(32-BINARY_BIT);}void test_long(long val){    cout<<"补码数字:"<<val<<"\n";    bitset<32> a(val);    cout<<"补码:"<<a.to_string().substr(32-BINARY_BIT)<<"\n";    cout<<"原码:"<<true_form_long(a.to_string())<<"\n";    cout<<"反码:"<<not_code(a.to_string())<<endl; //   bitset<32> b(true_form_long(a.to_string())); //   cout<<b.to_string()<<endl;}void test_string(const string& str){    if(str.size()==32)        cout<<"补码:"<<str.substr(32-BINARY_BIT)<<"\n";    else        {        string s(BINARY_BIT-str.size(),'0');        cout<<"补码:"<<s+str<<endl;        }    cout<<"原码:"<<true_form_long(str)<<"\n";    cout<<"反码:"<<not_code(str)<<endl;}int main(){    string str="1000001111000011010010010";    bitset<32> a(str);    cout<<a.to_ulong()<<endl;    cout<<true_form_long(str)<<endl;    for(long i=-10;i<0;i++)    {        test_long(i);        cout<<endl;    }    puts("输入补码");    string s;    cin>>s;    test_string(s);} 

热点排行