/** * Read bits from a number into a string * The string is limited to 0 and 1 * * @author gtowell * Created: April 2021 * **/ #include #include /** * readbits from a char using normal math * @param xx -- the char to be read * @param rtn -- a stirng into which to write the bits * **/ void pbMATH(unsigned char xx, char rtn[]) { for (int i = 7; i >=0; i--) { rtn[i] = '0' + (xx % 2); //printf("bit num=%1d value=%1d\n", i, xx % 2); xx /= 2; } } /** * readbits from a char using bit shifting * @param xx -- the char to be read * @param rtn -- a stirng into which to write the bits * **/ void pbBITS(unsigned char xx, char rtn[]) { for (int i = 7; i >=0; i--) { rtn[i] = '0' + (xx&1); //printf("bit num=%1d value=%1d\n", i, xx % 2); xx >>= 1; } } int main(int argc, char const *argv[]) { char aa[8]; for (int i = 1; i < argc; i++) { pbMATH(atoi(argv[i]), aa); printf("BITS:%s\n", aa); pbBITS(atoi(argv[i]), aa); printf("BITS:%s\n", aa); } return 0; }