문제

지금까지 지금까지 가지고있는 것은 다음과 같습니다.

void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
    unsigned char *buf = (unsigned char*)ptr;

    for( int i = 0; i < buflen; ++i ) {
        if( i % 16 == 0 ) {
            stream << prefix;
        }

        stream << buf[i] << ' ';
    }
}

Stream.Hex, stream.setf (std :: ios :: hex)를 시도하고 Google을 약간 검색하려고 시도했습니다. 나는 또한 시도했다 :

stream << stream.hex << (int)buf[i] << ' ';

그러나 그것은 작동하지 않는 것 같습니다.

다음은 현재 생성하는 일부 출력의 예입니다.

Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 

출력이 다음과 같이 보이길 바랍니다.

FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
도움이 되었습니까?

해결책

#include <iostream>
using namespace std;
int main() {
    char c = 123;
    cout << hex << int(c) << endl;
}

편집하다: 제로 패딩으로 :

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    char c = 13;
    cout << hex << setw(2) << setfill('0') << int(c) << endl;
}

다른 팁

char upperToHex(int byteVal)
{
    int i = (byteVal & 0xF0) >> 4;
    return nibbleToHex(i);
}

char lowerToHex(int byteVal)
{
    int i = (byteVal & 0x0F);
    return nibbleToHex(i);
}

char nibbleToHex(int nibble)
{
    const int ascii_zero = 48;
    const int ascii_a = 65;

    if((nibble >= 0) && (nibble <= 9))
    {
        return (char) (nibble + ascii_zero);
    }
    if((nibble >= 10) && (nibble <= 15))
    {
        return (char) (nibble - 10 + ascii_a);
    }
    return '?';
}

더 많은 코드 여기.

노력하다:

#include <iomanip>
....
stream << std::hex << static_cast<int>(buf[i]);

좀 더 구식을 사용하여 할 수 있습니다.

char buffer[3];//room for 2 hex digits and \0
sprintf(buffer,"%02X ",onebyte);

나는 보통 숫자를 반환하고 그냥 사용하는 함수를 만듭니다.

void CharToHex(char c, char *Hex)
{
   Hex[0]=HexDigit(c>>4);
   Hex[1]=HexDigit(c&0xF);
}

char HexDigit(char c)
{
   if(c<10)
     return c;
   else
     return c-10+'A';
}

chchar_t (유니 코드) 16 진 문자열에 숯

wchar_t* CharToWstring(CHAR Character)
{
wchar_t TargetString[10];
swprintf_s(TargetString, L"%02X", Character);

// then cut off the extra characters
size_t Length = wcslen(TargetString);

wchar_t *r = new wchar_t[3];
r[0] = TargetString[Length-2];
r[1] = TargetString[Length-1];
r[2] = '\0';
return r;
}

스트림을 한 번만 구성하면됩니다.

stream << std::hex << std::setfill('0') << std::setw(2)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top