bit testing in a 128bits bitmap, improvement?

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I want to test a bit in a 128bits bitmap, for the moment it is stored in 4 unsigned long, it looks like this:

unsigned long  pid01to20_support;
unsigned long  pid21to40_support;
unsigned long  pid41to60_support;
unsigned long  pid61to80_support;

static uint8_t is_pid_supported_32(uint8_t pid, unsigned long *bitmap)
{
	if (1L<<(uint8_t)(pid) & *bitmap )
		return 1;
	else
		return 0;
}

uint8_t is_pid_supported(uint8_t pid)
{
	// note that pid PID_SUPPORT00 (0x00) is always supported
	if(pid==0)
		return 1;
  else
	if(pid<=0x20)
	{
		if(is_pid_supported_32(0x20-pid, &pid01to20_support))
			return 1;
	}
  else
	if(pid<=0x40)
	{
		if(is_pid_supported_32(0x40-pid, &pid21to40_support))
			return 1;
	}
  else
	if(pid<=0x60)
	{
		if(is_pid_supported_32(0x60-pid, &pid41to60_support))
			return 1;
	}
  else
	if(pid<=0x80)
	{
		if(is_pid_supported_32(0x80-pid, &pid61to80_support))
			return 1;
	}

	return 0;
}

I was wondering what is the shortest (in term of bytes taken) to do this? Would it be better to use 2 uint64_t or an array of 16 uint8_t ?

Does someone has better code? is_pid_supported_32() is 58 bytes and is_pid_supported() is 92 bytes, I'm sure it can be done in less than 150 bytes (in C), does someone want to do the challenge?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
uint8_t my128bits[16];

uint8_t bitmask[] = { 1, 2, 4, 8, 16, 32, 64, 128 };

uint8_t testbit( uint8_t *array, uint8_t index )
{
  return array[index >> 3] & bitmask[index & 7];
}

Peter

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks Peter, I think I came to the same result!

return bitmap[pid>>3] & 1<<(pid&7);

it was so simple :D