编写c语言程序实现字符串与2进制相互转换
时间: 2024-05-02 17:18:09 浏览: 23
1. 字符串转换成二进制
```
#include <stdio.h>
#include <string.h>
void stringToBinary(char* s) {
int len = strlen(s);
for (int i = 0; i < len; i++) {
for (int j = 7; j >= 0; j--) {
printf("%d", (s[i] >> j) & 1);
}
printf(" ");
}
}
int main() {
char s[] = "hello world";
stringToBinary(s);
return 0;
}
```
2. 二进制转换成字符串
```
#include <stdio.h>
#include <string.h>
void binaryToString(char* s) {
int len = strlen(s);
for (int i = 0; i < len; i += 8) {
char c = 0;
for (int j = 0; j < 8; j++) {
c = c << 1;
c += s[i+j] - '0';
}
printf("%c", c);
}
}
int main() {
char s[] = "01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100";
binaryToString(s);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)