简体   繁体   English

如何在C中将位数组的元素传递给函数

[英]How to pass element of bit array into function in C

I would like to know how to pass an element of a bit array into a function in C language. 我想知道如何将位数组的元素传递给C语言的函数。 I want to control the function execution by this "logic" signal. 我想通过此“逻辑”信号控制功能的执行。 My idea is that some function sets or clears dedicated element of a bit array and this action changes behavior of my function but I don't know how to declare the function prototype (I don't how to say the compiler that the function expects bit array element as one of his arguments). 我的想法是某些函数设置或清除位数组的专用元素,并且此操作会更改我的函数的行为,但是我不知道如何声明函数原型(我不说该函数期望位的编译器数组元素作为他的参数之一)。 Does it ever exist any trick how to use individual bit array elements in a C language function? 在C语言函数中如何使用单个位数组元素是否存在任何技巧? Thanks for any suggestions. 感谢您的任何建议。

It sounds like you are looking for some generic solution using function pointers. 听起来您正在寻找使用函数指针的一些通用解决方案。 That is, pass a function pointer which determines the action to take. 也就是说,传递一个函数指针,该指针确定要执行的操作。 Example: 例:

void bit_change (uint8_t*  arr, 
                 size_t    byte_index,
                 size_t    bit_index, 
                 action_t* action)
{
  arr[byte_index] = action(arr[byte_index], bit_index);
}

Where action_t is the function type determining the behavior. 其中action_t是确定行为的函数类型。 Now you can implement actions such as bit sets, bit clears, bit toggles, set all bits etc etc. 现在,您可以执行诸如位设置,位清除,位切换,设置所有位等操作。

Full example: 完整示例:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

typedef uint8_t action_t (uint8_t data, size_t bit);

uint8_t bit_set (uint8_t data, size_t bit)
{
  return (uint8_t) (data | (1u << bit));
}

uint8_t bit_clear (uint8_t data, size_t bit)
{
  return (uint8_t) (data & ~(1u << bit));
}


void bit_change (uint8_t*  arr, 
                 size_t    byte_index,
                 size_t    bit_index, 
                 action_t* action)
{
  arr[byte_index] = action(arr[byte_index], bit_index);
}


void print_array (size_t size, const uint8_t array[size])
{
  for(size_t i=0; i<size; i++)
  {  
    printf("%.2"PRIu8 " ", array[i]);
  }
  printf("\n");
}


int main (void)
{
  uint8_t array [5] = {0};

  bit_change(array, 0, 2, bit_set);
  print_array(sizeof(array), array);

  bit_change(array, 0, 2, bit_clear);
  print_array(sizeof(array), array);

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM