2009-03-08 14 views
14

Esto es lo que actualmente tengo hasta ahora:¿Cómo se escriben los valores hexadecimales de un carácter en ASCII en un archivo de texto?

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] << ' '; 
    } 
} 

He intentado hacer stream.hex, stream.setf (std :: ios :: hex), así como la búsqueda en Google para un poco. También lo intenté:

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

Pero eso tampoco parece funcionar.

Aquí es un ejemplo de alguna salida que produce actualmente:

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

Me gustaría que la salida se vea como la siguiente:

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 
+1

BTW: Usted debe use el prefijo const void * ptr y const char * para dejar en claro que no modificará estos búferes. – mmmmmmmm

+0

@rstevens: ¡Está bien! – xian

+1

es por eso que me gusta tanto el desbordamiento de pila. estos pequeños problemas divertidos surgen de vez en cuando y alguien arroja un fragmento de código y lo resuelve ... – MikeJ

Respuesta

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

Editar: con relleno de ceros:

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

¿Eso no solo lo enviará a la consola? – xian

+0

¿Podría explicar por qué debería funcionar de manera diferente al uso de stream.hex, como el asker ya probado? –

+0

Me parece un poco molesto el modificador de flujo 'hexadecimal'. Si está produciendo otros tipos, debe continuar cambiando la transmisión (usando 'dec' por ejemplo) y, hasta donde yo sé, no hace ceros a la izquierda. –

6
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 '?'; 
} 

Más código here.

0

por lo general hago una función que devuelve los dígitos y sólo lo utilizan:

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'; 
} 
-1

Usted sólo tendrá que configurar su torrente una vez:

stream << std::hex << std::setfill('0') << std::setw(2) 
+4

-1 [Esto está mal] (http://www.ideone.com/Xwjtz). ¿Cómo ha evitado los votos a la baja durante más de dos años? –

1

Probar:

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

También puede hacerlo usando algo un poco más pasada de moda:

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

CHAR a wchar_t (Unicode) HEX

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; 
} 
Cuestiones relacionadas