0
votes

I want to convert an integer into char array and retreive the same number from that char array.

Consider the number 20. As 1 int(4 bytes) = 1 char,

0000 0000 0000 0000 0000 0000 0001 0100 = (20) in decimal

___0 ___0 ___0 ___0 ___0 ___0 ___1 ___4 = hexadecimal representation

I want this pattern 00000014 to be stored in char array as 4 chars only as integer occupies 4 chars of space in such a way that the char array after converting into integer(can use sscanf()) will give the same result(20).

How do I do that?

2
You have tagged your question as both C and C++ instead of that language you are using. This is in contravention of the tags' usage directions. Please tag with only the language you are using, not multiple languages.ikegami

2 Answers

2
votes

You can use a union

union myUnion { 

    int x;
    char bytes[sizeof(int)]; 
}; 

And use it like:

union myUnion un;
un.x = 98632;

With this un.bytes hold the bytes of the integer 98632 in this case. If you change any of them, the change is reflected also in un.x, since everything in a union has a common memory location.

Conversion is handled automatically for you, if you want the int just get it by un.x and if you want the bytes get them by un.bytes. Whatever union member you change, the change is also made accordingly in its other members due to it being an union.

0
votes

Map each digit from 0 to 15 to it's equivalent 0 to f in hex. Apply a while loop taking remainder of the number when divided by 16 and append it to string and divide it by 16 in each step. The final string will be in reverse and I would keep it in reverse if there are operations to be done on it. If you want to print it, print it in reverse.

To convert the hex string back to int, reverse this procedure.

char mapping[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

void convert(string& s, int n)
{
    while (n)
    {
        int r = n % 16;
        s += mapping[r];
        n /= 16;
    }
}

int main()
{
    int n = 20;
    string s;
    convert(s, n);
    cout << s << endl;
}