二的补码函数的问题
Trouble with a Two's Complement Function
试图实现一个函数来返回一个字符串的二进制补码。我试了两个品种,结果很奇怪。
版本1(进行反转,但不进行"+1"):string twosComp(带符号整数){
string twosComp(signed int number) {
if ( number == 0 ) { return "1"; }
if ( number == 1 ) { return "0"; }
if ( number % 2 == 0 ) {
return twosComp(number / 2) + "1";
}
else {
return twosComp(number / 2) + "0";
}
}
版本2(反转并尝试"+1",但并不总是正确)
string twosComp(signed int number) {
bool bit = 0;
int size = 3; // not sure what to do about this, value could be -32768 to 32767
string twos;
number = ~abs(number) + 1;
for(int i = 0; i < size; i++) {
//Get right-most bit
bit = number & 1;
if(bit) {
twos += '1';
}
else {
twos += '0';
}
//Shift all bits right one place
number >>= 1;
}
return twos;
} // end twosComp
我一直在尝试这两个函数的各种迭代。我在这件事上没劲了。如果有人有更好的选择的话——在这一点上,我非常愿意接受建议。
(abs(number) ^ 0xffffffff) + 1
怎么样,然后将该值转换为字符串?
编辑:为什么是size = 3
?int是32位,通常是
下面的代码为一个短(16位)int执行您想要的操作:注意-我是用C而不是C++写的。。。
char* twosComplement(signed int n) {
static char s[17]; // static so the variable persists after the call
unsigned int i;
int j;
i = (2<<16)-n; // definition of twos complement
for(j=0;j<16;j++){
s[15-j] = ((i&1)==0)?'0':'1'; // test lowest bit
printf("%c", s[15-j]); // print for confirmation
i=i>>1; // right shift by one
}
printf("n"); // just to make output look clean
s[16]=' '; // terminate the string
return s;
}
int main() {
printf("the string is %sn", twosComplement(15)); // just an example
}
为了参考,您可以查看下面的链接,以便在C++中使用位集将整数转换为2的补码:http://2scomplimentcpp.blogspot.com.au/
#include <iostream>
#include <bitset>
using namespace std;
int disp_number()
{
int i = 0;
cout << "Enter Intiger : " ;
cin >> i;
cout << "decimal : " << std::dec << i << endl;
cout << "hex : " << std::hex << i << endl;
cout << "oct : " << std::oct << i << endl;
cout << "Binary : " << (bitset<16>)i << endl;
cout << "Inverse : " << bitset<16>(~i) << endl;
i = (0 <= i)?i:(-1)*i;
cout << "One's compliment : " << ~(bitset<16>)i << endl;
int d = ((bitset<16>)i).flip().to_ulong();
cout << "Two's compliment : " << bitset<16>(++d) << endl;
return 0;
}
您可以使用bitset的to_string()方法将表示转换为字符串。
相关文章:
- Visual Studio中的函数声明和函数定义问题
- C++quit()函数中可能存在作用域问题
- 类似于strcat()的函数出现问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 类C++中的函数问题(LNK2019和LNK1120错误)
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 关于简单C++函数(is_palindrome)的逻辑的问题
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- constexpr构造函数需要常量成员函数时出现问题
- 添加存储在向量中的大整数的函数出现问题
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 关于 c++ 函数中指针赋值的简单问题
- 如何在标头中声明(或定义)函数的问题
- 有关 c++ 构造函数的问题
- 模板类转换问题 - 无法推断调用的函数
- 从 C++ 中的函数返回数组地址问题
- 关于复制构造函数的一个棘手问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题