前言

二进制是一个值01010101,而字符串是一些字符后面加上’\0’,”01010101”.
当我们要将这两种形式进行转换的时候,可以运用位运算符,和某两个算法解决。

字符串——>数值

  • 先将数值变量向左移动,再用*取出字符串中的字符,-‘0’转换成数值,添加到变量中。
1
2
3
4
5
6
7
8
9
10
11
int btoi(char * st)
{
int num = 0;
while (*st)//到空字符结束,8个数,循环8次
{
num = (num << 1);//左移动
num += (*st++ - '0');//从左往右取字符,并转换成数值,添加到num
}

return num;
}

数值——>字符串

  1. 传递给函数,数值,和要准备存储的字符数组。
  2. 取最后一位数(运用8进制的掩码操作01 & num),并将其转换成字符,+ '0'添加到数组中。
    掩码:运用&运算符,用0覆盖掉1,0也为0
  3. 然后,将num进行移位的同时,赋值给num。num >>= 1
  4. for循环遍历数组中的元素除最后一个
  5. 最后在数组中最后一个元素赋值’\0’
1
2
3
4
5
6
7
8
9
char *itobs(int num, char *st)
{
int i;
const static int size = CHAR_BIT * sizeof(int);
for (i = size - 1; i >= 0; i--, num >>= 1)
st[i] = (01 & num) + '0';
st[size] = '\0';
return st;
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<stdio.h>
#include<string.h>
#include<limits.h>
int bstoi(char *);//二进制字符串转化为整数的函数
char * itobs(int , char *st); //整数转化为二进制字符串的函数
void show_bstr(const char * st); //4位一组显示二进制字符串
int main(int argc, char *argv[])
{
int n1, n2;
//分配一个int二进制形式的最大字符的字符串
char bin_st[CHAR_BIT * sizeof(int) + 1];//预备存储字符串的数组

n1 = bstoi(argv[1]);
n2 = bstoi(argv[2]);
show_bstr(itobs(~n1, bin_st));
show_bstr(itobs(~n2, bin_st));
show_bstr(itobs(n1 & n2, bin_st));
show_bstr(itobs(n1 | n2, bin_st));
show_bstr(itobs(n1 ^ n2, bin_st));

return 0;
}

int bstoi(char * str)
{
int num = 0;
while(*str)
{
num = num << 1;
num += (*str++ - '0');
}
return num;
}

char *itobs(int num, char *st)
{
int i;
const static int size = CHAR_BIT * sizeof(int);
for (i = size - 1; i >= 0; i--, num >>= 1)
st[i] = (01 & num) + '0';
st[size] = '\0';
return st;
}
void show_bstr(const char * st)
{
int i = 0;

while (st[i])
{
putchar(st[i]);
if (++i % 4 == 0 && st[i])
putchar(' ');
}
printf("\n");
}
左旋转二进制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<stdio.h>
#include<limits.h>
#define SIZE CHAR_BIT * sizeof(unsigned int)
unsigned int rotate(unsigned int , int);
void show_bstr(const char * st);
char * itobs(char *, unsigned int x);
int main()
{
char st[SIZE + 1];
unsigned int x = -3;
int s = 10;
show_bstr(itobs(st, x));
x = rotate(x, s);
show_bstr(itobs(st, x));

return 0;
}
unsigned int rotate(unsigned int n, int s)
{
for(int i = 0; i < s; i++)
{//要被丢弃的数,回到开头
n = (n << 1) + ((n >> (SIZE - 1)) & 01);
}
return n;
}

char *itobs(char * st, unsigned int n)
{
for(int i = SIZE - 1; i >= 0; i--, n >>= 1)
st[i] = (01 & n) + '0';
st[SIZE] = '\0';
return st;
}
void show_bstr(const char * st)
{
int i = 0;

while (st[i])
{
putchar(st[i]);
if (++i % 4 == 0 && st[i])
putchar(' ');
}
printf("\n");
}