C++ 如何使用链表将负十进制数转换为二进制数?

C++ 如何使用链表将负十进制数转换为二进制数?,c++,linked-list,C++,Linked List,我想用2的补码把一个负数转换成二进制数,但我不能给出一个正确的逻辑。如何使用链表将负十进制数转换为二进制数 我的一个朋友说这是一个有符号位之类的问题 我是一个初学者,无法找到解决这个问题的方法。我搜索了所有的网页,但什么也没找到 struct node { long data; node* next; }* head,* tail; int main(int argc, char** argv) { head = NULL; tail = NULL; l

我想用2的补码把一个负数转换成二进制数,但我不能给出一个正确的逻辑。如何使用链表将负十进制数转换为二进制数

我的一个朋友说这是一个有符号位之类的问题

我是一个初学者,无法找到解决这个问题的方法。我搜索了所有的网页,但什么也没找到

struct node {
    long data;
    node* next;
}* head,* tail;

int main(int argc, char** argv) {
    head = NULL;
    tail = NULL;
    long dec;
    cout << "Enter the decimal number" << endl;
    cin >> dec;
    div(dec);
    dis();
    singlecomp();
    dis();
    return 0;
}
void div(long num) {
    while (num != 0) {
        createNode(num % 2);
        num /= 2;
    }
}
void createNode(long val) {
    node* temp = new node;
    temp->data = val;
    temp->next = NULL;
    if (head == NULL) {
        head = tail = temp;

    } else {
        temp->next = head;
        head = temp;
    }
}

void dis() {
    node* cur = new node;
    cur = head;
    while (cur != NULL) {
        cout << cur->data << " ";
        cur = cur->next;
    }
}
void singlecomp() {
    node* now = new node;
    now = head;
    cout << endl;
    while (now != NULL) {
        if (now->data == 0) {
            now->data = 1;
        } else {
            now->data = 0;
        }
        now = now->next;
    }
}
struct节点{
长数据;
节点*下一步;
}*头,*尾;
int main(int argc,字符**argv){
head=NULL;
tail=NULL;
长十二月;
cout-dec;
分区(十二月);
dis();
singlecomp();
dis();
返回0;
}
无效div(长数值){
while(num!=0){
createNode(数量%2);
num/=2;
}
}
void createNode(长值){
node*temp=新节点;
温度->数据=val;
temp->next=NULL;
if(head==NULL){
头部=尾部=温度;
}否则{
温度->下一步=头部;
压头=温度;
}
}
无效dis(){
节点*cur=新节点;
cur=头部;
while(cur!=NULL){
下一步是收集数据;
}
}
void singlecomp(){
node*now=新节点;
现在=头;
cout数据==0){
现在->数据=1;
}否则{
现在->数据=0;
}
现在=现在->下一步;
}
}
  • 从C++11开始,负值的除法被指定为向零截断。在此之前,取整的方向是由实现定义的,从理论上讲,您的代码可能会在某些平台上导致无限循环

  • 对于当前的标准,C++允许负数的3种表示:

    • 符号震级
    • 补语
    • 二元补码
    您的代码实现了一个补码,而绝大多数计算平台(实际上我所知道的)都使用二个补码

  • C++长类型通常为32位或64位。您需要向补足的值添加足够的前导数,以填充当前算法未填充的位,因为它在达到值0时停止,而不是在枚举所有32或64位时停止

  • 在给定平台上生成有符号long的二进制表示的最简单方法是首先将其转换为无符号long,然后对无符号值使用除法/余数(或移位/位and)


  • 十进制到二进制的转换已经在
    cin>>dec
    完成。此后您要做的是隔离已经存在的二进制数字。@JamesZ Edit被拒绝。您的版本甚至无法编译。您的朋友收到了错误信息,或者您误解了。没有所谓的“签名位”。@user207421我的版本只是修复了你的代码布局。只有空格更改,这是一种自动的代码格式化。@JamesZ您的版本引入了不存在的运算符
    ->
    \嗯,其实我不知道。谢谢你的回复。你的建议很管用。