首页 > 解决方案 > 如何从c中的位读取char?

问题描述

我想通过移动它来修改一个char(从而改变它的值)并返回结果而不是之前的char:

#include <stdio.h>
#include <stdlib.h>

int main(){
    char * str = calloc(4, sizeof(char));
    printf("what bit to set [0-31]\n");
    int a;  
    scanf(" %i", &a);
    int byte = a/8;
    int offset = a%8;
    
    str[byte] = (str[byte] >> offset) & (char)255; //how to return the modified char? 
    
    for(int i =0; i<4 ; i++)
    {
        for (int j =0; j<8 ; j++)
            printf("%i", (str[i] >> (7-j)) & 1); //print the results
        printf("\n");
    }
}

输出

what bit to set [0-31]
20
00000000
00000000
00000000 // I want 00001000
00000000

标签: cbitmapcharbit

解决方案


推荐阅读