Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active November 4, 2016 17:29
Show Gist options
  • Save dhilst/5dca1b7b5956c7ea9a13c2ea8b2f715d to your computer and use it in GitHub Desktop.
Save dhilst/5dca1b7b5956c7ea9a13c2ea8b2f715d to your computer and use it in GitHub Desktop.
/*
* The MIT License (MIT)
*
* Copyright (c) <year> <copyright holders>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
/**
* @brief Converts a string containing to its binary counterpart. The string is
* expected to hold 2 characters for each byte, in hexdecimal notation.
*/
size_t hexstring_to_bin(char *buf, size_t bsiz, const char *str, size_t ssiz)
{
size_t i;
for (i = 0; i < bsiz && i*2 < ssiz; i++)
sscanf(&str[i*2], "%2hhx", &buf[i]);
return i;
}
/**
* @brief Print a number in binary. Keep aware of recursiveness
*/
void printbin(int i)
{
if (i > 1)
printbin(i/2);
printf("%d", i % 2);
}
/**
* An average with no need of arrays :)
*
* @param y The current point
* @param factor From 0.0 to 1.0. Smaller values will retain old points.
* @param ema The current expential moving average value
* @return A new exponential moving average value
*/
double exponential_moving_average(double y, double factor, double ema)
{
return factor * y + (1.0 - factor) * ema;
}
/**
* Return system clock in us
*/
unsigned long clock_gettime_us(void)
{
struct timespec ts;
unsigned long value;
clock_gettime(CLOCK_MONOTONIC, &ts);
value = (ts.tv_sec * 1e6 + ts.tv_nsec / 1e3);
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment