Skip to content

Instantly share code, notes, and snippets.

@sprive
Created September 1, 2022 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sprive/43b00c6945f2e84b403f81b66da5229d to your computer and use it in GitHub Desktop.
Save sprive/43b00c6945f2e84b403f81b66da5229d to your computer and use it in GitHub Desktop.
tinylog.c, log2 calculation for both FPU and no FPU
/* Simple log2 calculation; on FPU-less platform it will bitshift instead of log2 */
//
// linux/mac:
// clang -fdiagnostics-color=always -g ./tinylog.c -o ./tinylog
// CC65:
// cl65 -t atari ./tinylog.c -o tinylog.xex
// atari800 -nobasic -run ./tinylog.xex
#include<stdio.h>
#include<stdint.h>
// This isn't very portable because __CC65__ isn't the only FPU-less platform.
// Many embedded microcontrollers define __FPU_PRESENT 0, so the question is should CC65 also define __FPU_PRESENT?
#if defined (__CC65__)
#include<cc65.h>
#include<conio.h>
#warning "CC65 detected, so avoiding float operations."
#else
#include<math.h>
#endif /* __CC65__ */
int main(void)
{
uint16_t input; // number (range) limit, user-defined
uint16_t output;
output = 0;
printf("Input number you want log2 of:");
scanf("%hu", &input);
printf("You input: %d\n", input);
// get log2
// ... basically if we had _FPU_PRESENT we could just do:
///
#if defined (__CC65__)
while (input) {
input >>= 1;
output ++;
}
#else
output = (int)(log(input) / log(2))+1;
#endif /* __CC65__ */
printf("log2 result:%d\n", output);
// For platforms that clear the screen on exit, wait for user input
#if defined (__CC65__)
if (doesclrscrafterexit()){
printf("Press any key\n");
cgetc(); // conio.h
}
#endif /* __CC65__ */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment