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.
This is taking successive bytes from the buffer pointed to by
bufp, and putting them intovalue.The
value |= *bufp++ << shift;is taking the value atbufp(i.e., thecharat the addressbufpis pointing at) and ORing it with 8 bits ofvalue. Then it’s incrementingbufpto point go the next byte in the buffer. After that, it adds 8 toshift— that’s what determined which 8 bits ofvaluethe new bytes gets ORed. I.e.,shiftstarts as 0, so in the first iteration, the first byte ofbufpreplaces the bottom 8 bits ofvalue(replaces, because they’re starting out as 0). In the next iterator, the next byte ofbufpgets shifted left 8 bytes, to replace the next 8 bits ofvalue, and so on forlenbytes.Aside: if
lenis greater thansizeof(unsigned), this is going to write past the end ofvalue, causing undefined behavior.