-5

Is there a way where a couple of integers put into a string(by concatenation) and when that string is read character by character and printed as hex, the hex values of those numbers are equivalent to numbers themselves.

Example:

  • Lets say i have two numbers, 6 and 8 and a string "yahoo".

  • In the first step, i concatenate them and get a single string "6yahoo8" using snprintf().

  • In the next step, i read that string character by character and print out their hex values,

  • i want to obtain final output as:

    {0x06, 0x79, 0x61, 0x68, 0x6F, 0x6F, 0x08}.

  • But my program is printing the result:

    {0x36, 0x79, 0x61, 0x68, 0x6F, 0x6F, 0x38}.

    This result is correct except first and last byte. Any ideas how to accomplish the task like i wanted to? Advice is very much appreciated.

    The program i am using to form the string:

    string encode_url() {
        StringAccum sa;
        string url;
        const char *str = "yahoo";
        int p = 6;
        int q = 8;
        sa.snprintf(1,"%x", p);   // snprintf(len, format, value);
        sa << str.c_str();
        sa.snprintf(1, "%x", q);
        url = string(sa.take_string().c_str());
        return url;
    }
    

    There are some customary functions that we use like StringAccum, which is basically String Accumulator in C++.

1 Answers1

0

To find the reason you have to look into ASCII character codes.

if you convert the 8 in hexadecimal you will get 0x38. similar for 6 you will get 0x36.

why did you get 0x38 instead of 0x8 because here 8 is a string not a character variable (A bit less obvious than int is the other of the plain integral types, the char. It's basically just another sort of int, but has a different application).

Sumit Gemini
  • 1,766
  • 1
  • 14
  • 18