HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Function to extract bytes as a decimal

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
decimalfunctionbytesextract

Problem

You give this function a pointer and how many bytes you want to extract as a decimal and it returns it.

long long
byte_extract
(void * source, size_t bytes)
{
    long long num = 0, m = 1;
    size_t i;

    for(i = 0; i != bytes; i++)
    {
        num += (((unsigned char*)source)[i]*m);
        m<<=0x8;
    }
    return num;
}

Solution

It does the job, so that's good. It's quite clear and I don't see fundamental flaws in it. There are a few minor things I'd recommend to change:

-
The most important expression in the middle is a bit hard to read.
I find it much easier this way: num += m ((unsigned char) source)[i];
(Redundant parens removed, multiplication operands switched, minor spacing adjustments)

-
Instead of m

-
The name
byte_extract doesn't convey well what you described: "You give this function a pointer and how many bytes you want to extract as a decimal and it returns it." extract_num or extract_bytes_as_num would be better

-
Renaming
m to multiplier` could be a good idea too

Context

StackExchange Code Review Q#69204, answer score: 5

Revisions (0)

No revisions yet.