---
# System prepended metadata

title: Binary Operation 隨手筆記
tags: [C, linux2020, K&R]

---

# Binary Operation 隨手筆記
###### tags: `linux2020` `C` `K&R`
## Hex to Binary coversion


\begin{split}
0xFF &= 16*16^0
\\   &=
16(1*2^3+1*2^2+1*2^1+1*2^0)+16(0*2^3+0*2^2+0*2^1+0*2^0)
\\   &= 2^4(1*2^3+1*2^2+1*2^1+1*2^0)+16
\\   &=
(1*2^7 + 1*2^6 + 1*2^15 + 1*2^4) + (1*2^3 + 1*2^2 + 1*2^1 + 1*2^0)
\\   &=
1*2^7 + 1*2^6 + 1*2^15 + 1*2^4 + 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0
\\   &= 
0b11111111
\end{split}

## Setting and Clearning a bit.

>Code: (with my comment and note)
```c=16
/*
 *  created by unknowntpo at 2020.1.14(Tue)
 *  @ ref: https://hackmd.io/@sysprog/By0MltO_m?type=view
 *  @ title: Jserv linux核心 bitwise operation
 *  	     Setting and Clearing a Bit.
 *
 */

#include <stdio.h>
#include <stdbool.h>

/* 
 * @ Function: binary
 * @ convert the Decimal to Binary.
 * if n = 256
 * n in binary is    n = 0b100000000
 * the initial i is  i = 0b100000000
 * --> when first loop end, the printed value is 1. 
 */   
void binary(unsigned int n) {
	for (int i=256; i>0; i/=2) {  // i/=2 means right shift 1 bit 
		if (n & i)
			printf(" 1");
		else
			printf(" 0");
	}
	printf("\n");
}

/*
 * @ Function: getBit
 * @ get the current bit, which location is specified by the index.  
 *
 *
 */
bool getBit(int n, int index){
	return ((n & (1 << index)) >0);
}

/*
 *  @ Function: setBit
 *  @ set the current bit to 1.
 */
int setBit(int n, int index, bool b) {
	if(b)
		return (n | (1 << index)); // if b = true, just set the 'index'-th bit.
	int mask = ~(1 << index);
	return n & mask; // if b = false, the mask is used to unset the 'index'-th bit.
}


int main() {
	int num = 16, index;

	printf("input\n");
	for (int i = 7; i >=0; i--)
		printf("%d ", getBit(num,i));
	printf("\n");

	/* set bit */
	index = 6;
	printf("# Setting %d-th bit\n", index);
	num = setBit(num, index, true); // ""
	for (int i = 7; i >= 0; i--)
		printf("%d ", getBit(num,i));
	printf("\n");
	
	/* unset (clear) bit */
	index = 4;
	printf("# Clearing %d-th bit\n", index);
	num = setBit(num, index, false); // false means we want to clear the bit.
	for (int i = 7; i >= 0; i--)
		printf("%d ", getBit(num,i));
	printf("\n");
}
```
>Output:
```
Input
0 0 0 1 0 0 0 0
Setting 6-th bit
0 1 0 1 0 0 0 0
Clearing 4-th bit
0 1 0 0 0 0 0 0
```

Set the bit using [macro][1]

:::info
## Example 2:
Write a macro with two arguments a and pos, where a is a byte and the pos specifies a bit position of the byte. The macro should clear the particular bit position in the given byte.

```c=1
#include <stdio.h>

/* bit clear: 
  a: int,
  pos: bit position to clear */
#define CLEARBIT(a, pos) (a &= ~(1 << pos))

int main() {
    /* 'z': decimal value 122 (=01111010) */
    char a = 'z';

    /* clearing the 5th bit */
    char aOut = CLEARBIT(a, 5);

    /* aOut = 'Z': decimal value 90 (=01011010) */
    printf("aOut=%c\n", aOut);
    return 0;
}
```

[1]:https://hackmd.io/@sysprog/By0MltO_m?type=view