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

时间:2019-04-08 09:49:01

标签: c++ binary char hex

我曾尝试将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
}

因此,要查找错误,请删除“十六进制”

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

我使用了“无符号”,但是得到了负值。

我只是期望值“ 144”

如何解决此代码以获得正确的值?

1 个答案:

答案 0 :(得分:0)

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();
    }