Justin Kredible
Justin Kredible

Reputation: 8414

Explain what this function does

Can anyone explain, at a level that a novice C programmer would understand, what this function does?

unsigned getunsigned(unsigned char *bufp, int len) {
    unsigned value = 0;
    int shift = 0;
    while (len--) {
        value |= *bufp++ << shift;
        shift += 8;
    }
    return value;
}

I guess the line that's giving me the most trouble to wrap my head around is:

value |= *bufp++ << shift;

Also, can anyone provide a way to re-write this so that it is more clear for an inexperienced C programmer to understand?

I found this code online while doing research for an assignment and I prefer not to use it unless I understand fully what it's doing and how it's doing it.

Upvotes: 1

Views: 140

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490048

This is taking successive bytes from the buffer pointed to by bufp, and putting them into value.

The value |= *bufp++ << shift; is taking the value at bufp (i.e., the char at the address bufp is pointing at) and ORing it with 8 bits of value. Then it's incrementing bufp to point go the next byte in the buffer. After that, it adds 8 to shift -- that's what determined which 8 bits of value the new bytes gets ORed. I.e., shift starts as 0, so in the first iteration, the first byte of bufp replaces the bottom 8 bits of value (replaces, because they're starting out as 0). In the next iterator, the next byte of bufp gets shifted left 8 bytes, to replace the next 8 bits of value, and so on for len bytes.

Aside: if len is greater than sizeof(unsigned), this is going to write past the end of value, causing undefined behavior.

Upvotes: 5

Omkant
Omkant

Reputation: 9204

value |= *bufp++ << shift;

is equivalent to

value =  value | (*bufp << shift);
bufp++;

first value at bufp is shifted to the value in shift and the resultant is ORed | with value and then bufp is incremented.

At last value of shift is changed by shift +=8 means shift = shift + 8

So it takes all the bytes in the bufp because while loop won't terminate until len becomes 0.

Upvotes: 1

user541686
user541686

Reputation: 210352

value |= *bufp++ << shift;

is equivalent to

value = value | (*bufp << shift);
bufp++;

Upvotes: 1

Related Questions