数据转换-位串字节数组

utils.c

#include "utils.h"

int Bitstr2ByteArr(unsigned char *bs, unsigned char *ba, int *lba) {
    int i, j;
    for (i = 0, j = 0; j < *lba; j++) {
        ba[j] = 0;
        for (int k = 0; k < 8; k++) {
            if (bs[i] == '1') {
                ba[j] |= (1 << (7 - k));
            } else if (bs[i] != '0') {
                return -1; // 非法字符
            }
            i++;
        }
    }

    return 0;
}

int ByteArr2Bitstr(unsigned char *ba, unsigned char *bs, int *lbs) {
    int i, j;
    for (i = 0, j = 0; i < *lbs; i++) {
        for (int k = 7; k >= 0; k--) {
            bs[j++] = ((ba[i] >> k) & 1) + '0';
        }
    }
    
    bs[j] = '\0';
    *lbs = j;
    return 0;
}

测试代码

#include "utils.h"
#include <stdio.h>

int main() {
    unsigned char bs[] = "1010010100011100";
    unsigned char ba[3] = {0};
    int len = 3;

    if (Bitstr2ByteArr(bs, ba, &len) == 0) {
        printf("结果:ba = \"%02X%02X%02X\"; len = %d\n", ba[0], ba[1], ba[2], len);
    } else {
        printf("位串转换为字节串出错\n");
    }

    unsigned char ba2[] = {0x05, 0x1C};
    unsigned char bs2[17] = {0};
    int len2 = 17;

    if (ByteArr2Bitstr(ba2, bs2, &len2) == 0) {
        printf("结果:bs = \"%s\"\n", bs2);
    } else {
        printf("字节串转换为位串出错\n");
    }

    return 0;
}


posted @ 2024-06-06 14:59  20211312徐元琦  阅读(8)  评论(0编辑  收藏  举报