-
-
Save pancurster/3161010 to your computer and use it in GitHub Desktop.
Bit setter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void setbit(int* data, char from, char len, int val) | |
{ | |
unsigned int b = ~0; | |
b >>= sizeof(int)*8 - len; | |
*data &= ~(b << from-len); | |
*data |= (val << from-len); | |
} | |
void print_bits(int data) | |
{ | |
int a = sizeof(int)*8; | |
unsigned int mask = ~0; | |
mask <<= sizeof(int)*8 - 1; | |
while(a) { | |
printf("%d", (data & mask) ? 1 : 0); | |
data <<= 1; | |
--a; | |
} | |
} | |
int main(int argc, char* argv[]) | |
{ | |
int value = atoi(argv[1]); | |
printf("val: %5d, 0x%04x, 0b", value, value); | |
print_bits(value); | |
puts(""); | |
if (argc == 5) { | |
int vls[3] = { atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) }; | |
setbit(&value, vls[0], vls[1], vls[2]); | |
printf("val: %5d, 0x%04x, 0b", value, value); | |
print_bits(value); | |
puts(""); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment