CString hex naar ASCII karakters

Status
Niet open voor verdere reacties.

Einsteinovic

Gebruiker
Lid geworden
22 dec 2008
Berichten
24
Hallo allemaal,

Weet iemand hoe ik in VC++(MFC) een hex string (CString) naar ascii karaters kan converteren?
Bijvoorbeeld hex "48414C4C4F" naar ascii "HALLO".

Alvast bedankt.
 
Met iets als het onderstaande bijvoorbeeld:

[cpp]
void HexStringToAsciiString(const char *hexString, char *asciiString)
{
int hexStringLength = strlen(hexString);
if (hexStringLength & 0x01) return; // ongeldige hexstring: oneven waarde!

char buffer[5] = "0x??";
int asciiIndex = 0, hexIndex = 0;

do
{
memcpy(&buffer[2], &hexString[hexIndex], 2);
asciiString[asciiIndex++] = strtol(buffer, NULL, 16);
hexIndex += 2;
}
while (hexIndex <= hexStringLength - 2);

asciiString[asciiIndex] = '\0';
}
[/cpp]

Aan te roepen via:

[cpp]
char *hexString = cstring.GetBuffer(cstring.GetLength());
char asciiString[255];
HexStringToAsciiString(hexString, asciiString);
[/cpp]

(foutafhandeling mag je zelf regelen)
 
Met iets als het onderstaande bijvoorbeeld:

[cpp]
void HexStringToAsciiString(const char *hexString, char *asciiString)
{
int hexStringLength = strlen(hexString);
if (hexStringLength & 0x01) return; // ongeldige hexstring: oneven waarde!

char buffer[5] = "0x??";
int asciiIndex = 0, hexIndex = 0;

do
{
memcpy(&buffer[2], &hexString[hexIndex], 2);
asciiString[asciiIndex++] = strtol(buffer, NULL, 16);
hexIndex += 2;
}
while (hexIndex <= hexStringLength - 2);

asciiString[asciiIndex] = '\0';
}
[/cpp]

Aan te roepen via:

[cpp]
char *hexString = cstring.GetBuffer(cstring.GetLength());
char asciiString[255];
HexStringToAsciiString(hexString, asciiString);
[/cpp]

(foutafhandeling mag je zelf regelen)

Dank je wel. Ik heb cstring = "01 48 61 6c 6c 6f"; als voorbeeld getest en hij doet het nog niet. Ik krijg asciistring = "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ". Of moet cstring met 0x beginnen? zoiets cstring = "0x01 0x48...."
Nogmaals bedankt
 
Ik heb "48414C4C4F" als voorbeeld genomen (aan de code kan je in principe ook zien dat hij telkens twee tekens neemt (asciiwaarde in hex) en dus geen spaties verwacht)
 
Ow ja, en de lengte van de asciiString is uiteraard hexString/2+1 (null-byte).
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan