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

  • 4
    Please stop using the term "C/C++". –  Dec 08 '16 at 07:00
  • 1
    @NickyC I had put a better version of the same, :P – Sourav Ghosh Dec 08 '16 at 07:01
  • 2
    when you put number into string it becomes a char, and ASCII code for '6' is 36. – Photon Dec 08 '16 at 07:01
  • It is not clear what "this task" is. If it's making the equality `'6' == 6` hold, then no, there's no way. – n. m. could be an AI Dec 08 '16 at 07:02
  • Do not use `snprintf`. – BLUEPIXY Dec 08 '16 at 07:03
  • 1
    The reason behind why you need this is absolutely vexing me. It has the pungent aroma of an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Regardless, If you want to store a (very range-limited) number at the beginning or end of your `char` buffer, don't convert it; just store it directly in the appropriate character slot (i.e. don't use `snprintf`. – WhozCraig Dec 08 '16 at 07:04
  • 2
    @SouravGhosh Okay, you win. –  Dec 08 '16 at 07:05

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,836
  • 1
  • 15
  • 19