You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于偏移量和长度设置数组二进制字段的C函数开发

How to Implement a C Function to Set Binary Fields in an Array

Understanding the Example

First, let's align on the logic from your example to make sure we're on the same page:

  • Original array (binary bytes): 01101011 10010101 11001011 11010001 11000101 00101011
  • Buffer: 10011001 01011011 10100010
  • Offset = 5 (0-indexed bit position), Length = 7
  • We need to write the first 7 bits of the buffer (1001100) into the original array starting at bit 5, resulting in: 01101100 11000101 11001011 11010001 11000101 00101011

The core challenge here is working with bit-level operations since we're manipulating individual bits that may span multiple byte boundaries.

Core Implementation

Here's a clear, commented function that handles this logic:

#include <stddef.h>
#include <stdint.h>

// Returns 0 on success, -1 if input parameters are invalid
int set_binary_field(unsigned char *original, size_t original_len,
                     const unsigned char *buffer, size_t buffer_len,
                     size_t offset, size_t length) {
    // Calculate total bits available in the original array and buffer
    const size_t original_total_bits = original_len * 8;
    const size_t buffer_total_bits = buffer_len * 8;

    // Validate inputs to prevent out-of-bounds memory access
    if (offset >= original_total_bits || length == 0 ||
        offset + length > original_total_bits || length > buffer_total_bits) {
        return -1;
    }

    // Iterate over each bit we need to set
    for (size_t i = 0; i < length; i++) {
        // Find which byte and bit position this corresponds to in the original array
        const size_t orig_byte_idx = (offset + i) / 8;
        const uint8_t orig_bit_pos = 7 - ((offset + i) % 8); // MSB = bit 7, LSB = bit 0

        // Find the source bit's position in the buffer
        const size_t buf_byte_idx = i / 8;
        const uint8_t buf_bit_pos = 7 - (i % 8);

        // Extract the target bit from the buffer
        const uint8_t buf_bit = (buffer[buf_byte_idx] >> buf_bit_pos) & 0x01;

        // Clear the target bit in the original array, then set it to the buffer's bit value
        original[orig_byte_idx] &= ~(1 << orig_bit_pos);
        original[orig_byte_idx] |= (buf_bit << orig_bit_pos);
    }

    return 0;
}

Key Details Explained

  1. Bit Position Mapping:
    • Each byte's leftmost bit (MSB) is treated as the first bit in the binary string. So bit position k (0-indexed left-to-right) maps to byte k/8, and within that byte, bit 7 - (k%8) (since bytes store MSB as bit 7).
  2. Input Validation:
    • We check that the offset + length doesn't exceed the original array's total bits, and that the buffer has enough bits to cover the requested length—critical to avoid crashes or undefined behavior.
  3. Bit Manipulation:
    • For each bit, we first clear the target bit in the original array using & ~(1 << orig_bit_pos), then set it to the value from the buffer using | (buf_bit << orig_bit_pos).

Testing the Function

Let's verify this with your example using a test program:

#include <stdio.h>

// Helper to print the binary representation of the array
void print_binary_array(const unsigned char *arr, size_t len) {
    for (size_t i = 0; i < len; i++) {
        for (int j = 7; j >= 0; j--) {
            printf("%d", (arr[i] >> j) & 0x01);
        }
        printf(" ");
    }
    printf("\n");
}

int main() {
    // Original array (matches your example: 0x6B, 0x95, 0xCB, 0xD1, 0xC5, 0x2B)
    unsigned char original[] = {0x6B, 0x95, 0xCB, 0xD1, 0xC5, 0x2B};
    const size_t original_len = sizeof(original) / sizeof(original[0]);

    // Buffer (matches your example: 0x99, 0x5B, 0xA2)
    const unsigned char buffer[] = {0x99, 0x5B, 0xA2};
    const size_t buffer_len = sizeof(buffer) / sizeof(buffer[0]);

    printf("Original array:\n");
    print_binary_array(original, original_len);

    // Set the field: offset=5, length=7
    const int result = set_binary_field(original, original_len, buffer, buffer_len, 5, 7);
    if (result != 0) {
        printf("Error: Invalid parameters!\n");
        return 1;
    }

    printf("\nModified array:\n");
    print_binary_array(original, original_len);

    return 0;
}

When you run this, the output will match your expected result:

Original array:
01101011 10010101 11001011 11010001 11000101 00101011 

Modified array:
01101100 11000101 11001011 11010001 11000101 00101011 

Optimization Tip

For large arrays or long lengths, you can optimize this function to handle full bytes first (instead of iterating bit-by-bit) to boost performance:

  1. Handle the leading partial byte (if the offset isn't byte-aligned)
  2. Copy full bytes from the buffer to the original array
  3. Handle the trailing partial byte

This reduces the number of bitwise operations and leverages faster byte-level memory copies.

内容的提问来源于stack exchange,提问作者MOHAMED

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:09:10