82 lines
1.7 KiB
C++
Raw Normal View History

2016-12-17 20:59:03 +01:00
//
// FILE: nibbleArray.cpp
// AUTHOR: Rob Tillaart
2021-12-22 13:28:44 +01:00
// VERSION: 0.2.3
2020-11-27 11:28:57 +01:00
// PURPOSE: Arduino library for a compact array of nibbles (4 bits)
// URL: https://github.com/RobTillaart/nibbleArray
2016-12-17 20:59:03 +01:00
//
2021-01-29 12:31:58 +01:00
// HISTORY:
2021-11-10 19:53:12 +01:00
// 0.1.0 2015-04-12 initial version
// 0.2.0 2020-06-21 refactor; #pragma once; removed pre 1.0 support
// 0.2.1 2020-01-02 Arduino-CI + unit test
// 0.2.2 2020-11-10 update Arduino-CI, badges
// fix bug in setAll();
// add memory();
2021-12-22 13:28:44 +01:00
// 0.2.3 2021-12-22 update library.json, readme, license, minor edits
2021-01-29 12:31:58 +01:00
2016-12-17 20:59:03 +01:00
#include "nibbleArray.h"
2021-01-29 12:31:58 +01:00
2021-11-10 19:53:12 +01:00
nibbleArray::nibbleArray(const uint16_t size)
2016-12-17 20:59:03 +01:00
{
2021-11-10 19:53:12 +01:00
_size = size;
if (_size > (uint16_t) NIBBLEARRAY_MAXSIZE)
{
_size = (uint16_t) NIBBLEARRAY_MAXSIZE;
}
_bytes = (_size + 1)/2;
_arr = (uint8_t *) malloc(_bytes);
2016-12-17 20:59:03 +01:00
}
2021-01-29 12:31:58 +01:00
2016-12-17 20:59:03 +01:00
nibbleArray::~nibbleArray()
{
2021-11-10 19:53:12 +01:00
if (_arr != NULL)
{
free(_arr);
}
2016-12-17 20:59:03 +01:00
}
2021-01-29 12:31:58 +01:00
2021-11-10 19:53:12 +01:00
uint8_t nibbleArray::get(const uint16_t index)
2016-12-17 20:59:03 +01:00
{
2021-11-10 19:53:12 +01:00
if (index > _size)
{
return NIBBLEARRAY_ERROR_INDEX; // disable this check for more speed
}
if (index & 1) return _arr[index/2] & 0x0F;
return _arr[index/2] >> 4;
2016-12-17 20:59:03 +01:00
}
2021-01-29 12:31:58 +01:00
2021-11-10 19:53:12 +01:00
uint8_t nibbleArray::set(const uint16_t index, uint8_t value)
2016-12-17 20:59:03 +01:00
{
2021-11-10 19:53:12 +01:00
if (index > _size)
{
return NIBBLEARRAY_ERROR_INDEX; // disable this check for more speed
}
2020-11-27 11:28:57 +01:00
uint8_t v = value & 0x0F;
2021-11-10 19:53:12 +01:00
if (index & 1) _arr[index/2] = (_arr[index/2] & 0xF0) | v;
else _arr[index/2] = (_arr[index/2] & 0x0F) | (v << 4);
2020-11-27 11:28:57 +01:00
return NIBBLEARRAY_OK;
2016-12-17 20:59:03 +01:00
}
2021-01-29 12:31:58 +01:00
2020-11-27 11:28:57 +01:00
void nibbleArray::clear()
{
2021-11-10 19:53:12 +01:00
memset(_arr, 0, (_size + 1)/2);
2020-11-27 11:28:57 +01:00
}
2021-01-29 12:31:58 +01:00
2021-11-10 19:53:12 +01:00
void nibbleArray::setAll(uint8_t value)
2020-11-27 11:28:57 +01:00
{
2021-11-10 19:53:12 +01:00
uint8_t v = value & 0x0F;
v |= (v << 4);
memset(_arr, v, (_size + 1)/2);
2020-11-27 11:28:57 +01:00
}
2021-12-22 13:28:44 +01:00
2020-11-27 11:28:57 +01:00
// -- END OF FILE --
2021-12-22 13:28:44 +01:00