如何在C ++中将二进制转换为十六进制

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在C ++中将二进制转换为十六进制相关的知识,希望对你有一定的参考价值。

我已经尝试过将Binary转换为Hex

我的环境是Mac中的Xcode

这是我的代码:

string bytes2hex(string str)

    stringstream ss;
    string sub = str.substr(6,1);           // output : \220

    const char *sub_cstr = sub.c_str();
    cout << *sub_cstr << endl;              // output : \220

    ss << hex << unsigned (*sub_cstr);      
    cout << "ss : " << ss.str() << endl;    

    return ss.str();


int main()

    bytes2hex(sha256("88"));                 // ss : ffffff90

所以,要找到错误,请删除'hex'

ss << unsigned (*sub_cstr);                  // output : -112

我使用'unsigned'但我得到了负值。

我只期望价值'144'

如何修复此代码以获取正确的值?

答案
try that and see if it's working.   let's say the binary is 1101, then it will be 44D.

#include<iostream.h>
    #include<conio.h>
    void main()
    
        clrscr();
        long int binnum, rem, quot;
        int i=1, j, temp;
        char hexdecnum[100];
        cout<<"Enter Binary Number : ";
        cin>>binnum;
        quot = binnum;
        while(quot!=0)
        
            temp = quot % 16;
            // To convert integer into character
            if( temp < 10)
            
                temp = temp + 48;
            
            else
            
                temp = temp + 55;
            
            hexdecnum[i++]= temp;
            quot = quot / 16;
        
        cout<<"Equivalent hexadecimal value of "<<binnum<<" is :\n";
        for(j=i-1 ;j>0;j--)
        
            cout<<hexdecnum[j];
        
        getch();
    

以上是关于如何在C ++中将二进制转换为十六进制的主要内容,如果未能解决你的问题,请参考以下文章

在C中从二进制转换为char

在 C 中将 ascii char[] 转换为十六进制 char[]

如何在C中将十六进制字符串转换为二进制字符串?

如何在 c#.net 中将十六进制转换为十进制? [复制]

如何在 Visual C++ 中将字节数组转换为十六进制字符串?

如何在Perl中将十六进制转换为字符串