Error with ASCII to Hex conversion

Hi lads

i am a newbie at C++ so i am learning slowly

i am testing the following example code to convert ASCII to Hex data but the output somehow is showing extra FFFFFFF

thats the code


// hex numbers print.cpp : main project file.

#include "stdafx.h"
#include <algorithm>
#include <iostream>

void output_hex(char ch)
{
std::cout << std::hex << int(ch);
}

int main(int argc, char **argv)
{
std::string str(">áĐ©ydQ@1$"); //ASCII data beeing converted

std::for_each(str.begin(), str.end(), output_hex);

system("PAUSE");

return 0;
}

and this is the output

1019ffffffe1ffffffc4ffffff90ffffffa9796451403124

the correct output should be
1019e1c490a9796451403124


Any ideas of whats wrong in the code ?
You're pass the value as a signed byte. You then cast that signed char to a signed int, with that cast.

When the high bit is set, the number is interpreted as a negative number, and that's where all those fffff things come from.

You can fix this by arranging for that function to receive an unsigned char.
Topic archived. No new replies allowed.