user3260595
user3260595

Reputation: 53

type cast to integer

Suppose I have

    unsigned char * buffer; // buffer len in 10000

I want to convert buffer+50 to buffer+54 to int. The following code works

    int c=(*((int *) (buffer+ 32));

But is there any better way to do this and how much instruction it should take ?

Thanks a lot.

Upvotes: 0

Views: 83

Answers (1)

Zac Howland
Zac Howland

Reputation: 15872

Something like this would work:

std::uint32_t convert_to_int32(std::uint8_t* buffer) // assume size 4
{
    std::uint32_t result = (static_cast<std::uint32_t>(buffer[0]) << 24) |
                           (static_cast<std::uint32_t>(buffer[1]) << 16) |
                           (static_cast<std::uint32_t>(buffer[2]) << 8) |
                           (static_cast<std::uint32_t>(buffer[3]));
    return result;
}

The main problem you will have with your current method is if you run into alignment issues (e.g. you attempt to cast the integer pointer from a point in the buffer that is not on an integer alignment barrier). The shifting method gets around that.

Upvotes: 1

Related Questions