简体   繁体   中英

c++ convert integer to 8 char hex, drop the first two char so that it is only a 6 char hex, and convert back to an integer

I have been searching and experimenting for many, many, hours now, and so far I have not been able to adapt any of the solutions I have come across to do what I want.

My goal is to take an integer (538214658) and convert it into an 8 character hex string (020148102). Then I want to drop the first two characters (0148102) and convert it back into an integer(1343746) which I am using as a key in a map array.

The solutions I've seen so far just convert an integer into hex string, but don't take into account the desired digit length.

I am able to print out just the first 6 characters using the following code:

Console_Print("%06X", form ? form->refID : 0)

So I thought that maybe I could use that technique to store it into a string, and then use iostream or sstream to convert it back to an integer, but none of my searches turned up anything I could use. And all of my experiments have failed.

Some help would be greatly appreciated.

EDIT: Below is my solution based on Klaus' suggestion:

uint32_t GetCoreRefID(TESForm* form)
{
    uint32_t iCoreRefID = 0;
    if (form)
    {
        uint32_t iRefID = (uint32_t)(form->refID);
        iCoreRefID = iRefID & 0x00ffffff;
    }
    return iCoreRefID;
}

There is no need to convert to a string representation.

Look the following example:

int main()
{
    uint32_t val = 538214658 & 0x00ffffff;
    std::cout << std::hex << val << std::endl;
    std::cout << std::dec << val << std::endl;

}

You have to learn that a value is still only a value and is not dependent on the representation like decimal or hex. The value stored in a memory area or a register is still the same.

As you can see in the given example I wrote your decimal value representation and remove the first two hexadecimal digits simply by do a bitwise and operation with the hexadecimal representation of a mask.

Furthermore you have to understand that the printing with cout in two different "modes" did not change the value at all and also not the internal representation. With std::dec and std::hex you tell the ostream object how to create a string from an int representation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM