EgerStu EgerStu - 9 days ago 5
C Question

What is this C function doing?

I understand that it's going to take in a number and return a character. I understand what each line of code is doing, but I can't really express what it's doing overall in a meaningful way. Any ideas?

int function(uint64_t P1)
{
uint64_t L1 = P1;
uint32_t L2 = 1;

while (L1 > 15){

L2= (uint64_t)L2 << 4;
L1= L1 >> 4;

}
uint32_t L3 = 0;

while (L2 != 0){
L1 = P1;
uint32_t L4 = 0;

L4 = L1 % L2;
uint64_t L5 = (uint64_t)L4;
sub_function(L1/L2);
L3++;
P1 = L5;
L2= (uint64_t)L2 >> 4;
}
L1 = L3;

return L1;
}

void sub_function(uint64_t P1)
{
if (P1<= 9){
printf("%c", P1+48);
}
else{
printf("%c", P1+55);
}
}

Answer

This code accepts a decimal value and prints the hexadecimal representation.

Try it out yourself

In C++, we can instead use the std::hex stream manipulation flag on iostream to achieve the same result:

std::cout << std::hex << 16 << std::endl; // 10
std::cout << std::hex << 42 << std::endl; // 2a