简体   繁体   中英

C++: the fastest way to access specific octet of int

Assuming we have 32bit integer, 8bit char, gcc compiler and Intel architecture:

What would be the fastest way (with no assembler usage) to extract, say, third octet of integer variable? To store it to a char of some specific place of char[] for example?

For the 3rd octet (little endian):

int i = 0xdeadbeef;
char c = (char) (i>>16); // c = 0xad

use a Union :

union myCharredInt
{
    int myInt;
    struct {
        char char1;
        char char2;
        char char3;
        char char4;
    }
};

myCharredInt a = 5;

char c = a.char3;

shift the octet to the least significant octet and store it

somewhat like this but it depends exactly what you mean by 3rd octet, as the majority of my experience has been in big-endian architecture

char *ptr;
....
*ptr = val >> 8;

Whenever you are looking for the "fastest" or "best" way to do something in very particular circumstances, the answer almost always will be: experiment, and find out.

While there are rules of thumb to follow, they will not conclusively give you the best answer for your particular system, architecture, compiler, etc.

You will notice there are a few different answers to your question already, using different techniques.

How will you know which is best?

Answer: Try them out. Profile them.

Nb: I'm being a little facetious. I suspect what you really want to know is how to do this at all, and not how to do it fastest.

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