-2

I am reading a line of characters from the command line i.e.

progname 0102030405060708

argv[1] is of type char *argv[]

Than argv[1] is 0102030405060708

This is supposed to be used as a list of 8 characters in their hex representation.
What I need to do is take this value and divide it up into its parts. i.e.

01, 02, 03, 04 ...

And use them as hex values.

Essentially I need to get the char that 01, 02, 03.... in hex represent

I am not sure how to do this. Any help would be greatly appreciated.

Ran Eldan
  • 1,350
  • 11
  • 25
user2177896
  • 107
  • 1
  • 2
  • 7
  • 10
    Have you tried anything? – Rapptz Jul 18 '13 at 21:40
  • If you give us your expected output for this case, your aim would be clearer. Currently, it's hard to tell _exactly_ what you want to achieve. Also, you can achieve the splitting by accepting the 2 character strings separated by spaces. They would then exist from `argv[1]` to `argv[argc - 1]`. – user123 Jul 18 '13 at 21:43
  • possible duplicate of this question http://stackoverflow.com/questions/3408706/hex-string-to-byte-array-in-c – nio Jul 18 '13 at 21:43

2 Answers2

2

You can either split the string and work on the 2 chars long tokens or, save some memory (the extra 16B in this case should not matter but it is a good practice) and do it "in-place". I will only describe the 2nd way I mentioned.

You need a loop which will iterate over that string, advancing 2 chars at a time. Each iteration you want to convert the 2 chars number into actual char, a tip on how to do that is using the multiplying operator and the base of the numeric system those numbers are using (in this case 16).

You can store the result of each iteration and print afterwards or, more conveniently, print it each iteration.

Kelm
  • 967
  • 5
  • 14
0

Assuming I've understood you correctly, I think you can do this fairly neatly with string streams.

std::stringstream stream(argv[1]);
std::string twochars;
while (stream >> std::setw(2) >> twochars) {
  int num;
  std::stringstream twocharstream(twochars);
  twocharstream >> std::hex >> num;
  // Do something with the number here
}

You start by streaming two characters at a time into the string twochars. Then you create another stream from those two chars which you stream into an integer using the hex manipulator to convert as hexadecimal.

If you need the character represented by the number (i.e. 41 is the character 'A'), then you can simply do:

char c = num;
James Holderness
  • 22,721
  • 2
  • 40
  • 52