Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
static int ng_count = 0;
#define TEST_EQUAL(expect, v) do { if ((v) != (expect)) { \
printf("Failed @__%d__: v=%02x expect=%02x", __LINE__, (v), (expect)); \
printf("\n v:"); \
DEC2BIN((v)); \
printf("\n e:"); \
DEC2BIN((expect)); \
printf("\n"); \
ng_count++; } } while(0);
// for debug
static void DEC2BIN(unsigned char val)
{
char binstr[9] = "";
binstr[8] = '\0';
int i;
for (i=7; i>=0; i--) {
binstr[i] = (val & 0x01) ? ('1') : ('0');
val >>= 1;
}
printf("%s ", binstr);
}
static uint8_t replace_bits(uint8_t src, uint8_t replace, int offset, int len)
{
uint8_t mask = (~(0xFF << len)) << offset;
return (src & ~mask) | (replace & mask);
}
int main(int argc, char *argv[])
{
/**
* [bit]
* source: 00000000
* replace: 1111
* -----------------
* dest: 00011110
*/
TEST_EQUAL(0b00011110, replace_bits(0b00000000, 0b11110, 1, 4));
TEST_EQUAL(0b00011110, replace_bits(0b00000000, 0b11111111, 1, 4));
TEST_EQUAL(0b00011110, replace_bits(0b00000000, 0b00011110, 1, 4));
/**
* [bit]
* source: 11111111
* replace: 0000
* -----------------
* dest: 11100001
*/
TEST_EQUAL(0b11100001, replace_bits(0b11111111, 0b00000, 1, 4));
TEST_EQUAL(0b11100001, replace_bits(0b11111111, 0b00000000, 1, 4));
TEST_EQUAL(0b11100001, replace_bits(0b11111111, 0b11100001, 1, 4));
/**
* [bit]
* src: 11001110
* replace: 0101
* -----------------
* dst: 11000101
*/
TEST_EQUAL(0b11000101, replace_bits(0b11001110, 0b0101, 0, 4));
TEST_EQUAL(0b11000101, replace_bits(0b11001110, 0b11110101, 0, 4));
/**
* [bit]
* src: 11001101
* replace: 01101
* -----------------
* dst: 10110101
*/
TEST_EQUAL(0b10110101, replace_bits(0b11001101, 0b00110100, 2, 5));
/**
* [bit]
* src: 10101010
* replace: 010
* -----------------
* dst: 10010010
*/
TEST_EQUAL(0b10010010, replace_bits(0b10101010, 0b010000, 3, 3));
/**
* [bit]
* src: 11101010
* replace: 0101
* -----------------
* dst: 01011010
*/
TEST_EQUAL(0b01011010, replace_bits(0b11101010, 0b01010000, 4, 4));
TEST_EQUAL(0b01011010, replace_bits(0b11101010, 0b01011111, 4, 4));
if (ng_count == 0) printf("All tests is Passed.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment