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

问题描述 投票:0回答:1

我已经尝试过将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'

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

c++ binary char hex
1个回答
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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.