Skip to content

Instantly share code, notes, and snippets.

@alexlnkp
Created August 16, 2024 18:43
Show Gist options
  • Save alexlnkp/5648568b08647e2f9970547e6d98f55c to your computer and use it in GitHub Desktop.
Save alexlnkp/5648568b08647e2f9970547e6d98f55c to your computer and use it in GitHub Desktop.
Compact storage of time using bitwise operations
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef short unsigned int tt;
typedef unsigned char byte;
tt TimeToTT(char *time_string) { /* example input: "12:24AM" */
char *hour_string = strtok(time_string, ":"); byte hours = atoi(hour_string);
char *min_string = strtok(NULL, ":"); byte minutes = atoi(min_string);
bool is_pm = strstr(&min_string[strlen(min_string) - 2 - 1], "PM");
tt res = 0;
res |= is_pm; /* 1 bit */
res |= (minutes << 1); /* 6bits */
res |= (hours << 6); /* 4bits */
return res;
}
char* TTtoTime(tt a) {
char* res = malloc(7 * sizeof(char));
res[0] = '\0';
unsigned short hours = (a >> 6); /* 4 most left bits */
unsigned short minutes = (a >> 1) & 0x1F; /* 6 most right bits */
bool is_pm = a & 0x01; /* 1 most right bit */
char* hrs_str = malloc(sizeof(char) * 3); sprintf(hrs_str, "%u", hours);
strcat(res, hrs_str);
strcat(res, ":");
char* min_str = malloc(sizeof(char) * 3); sprintf(min_str, "%u", minutes);
strcat(res, min_str);
strcat(res, (is_pm ? "PM" : "AM"));
return res;
}
int main(void) {
char time[] = "3:24PM";
tt res = TimeToTT(time);
printf("TT value: %d\n", res); /* 241 */
char* time_reconstructed = TTtoTime(res);
printf("Reconstructed time: %s", time_reconstructed); /* 3:24PM */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment