C语言string类型转二进制数据
时间: 2023-10-17 18:09:56 浏览: 36
可以使用一个循环将每个字符转换成二进制形式,并将它们拼接成一个二进制数。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World!";
int len = strlen(str);
int i, j, val;
for (i = 0; i < len; i++) {
val = str[i];
for (j = 7; j >= 0; j--) {
printf("%d", (val >> j) & 1);
}
}
printf("\n");
return 0;
}
```
这段代码的输出结果将是该字符串对应的二进制数。
相关问题
c语言怎么将string转换成二进制
在C语言中,将字符串转换为二进制可以使用标准库函数atoi()和itoa()。
其中,atoi()函数可以将字符串转换为整型数,例如:
```c
char str[] = "1001";
int num = atoi(str);
```
在上述代码中,将字符串"1001"转换为了整型变量num的值为9,因为字符串表示的是二进制数,而atoi()函数默认将字符串解释为十进制数。
而itoa()函数则可以将整型数转换为指定进制的字符串,例如:
```c
int num = 9;
char str[10];
itoa(num, str, 2);
```
在上述代码中,将整型变量num的值9转换为了二进制字符串"1001"。其中,itoa()函数的第一个参数是要转换的整型数,第二个参数是转换后的字符串存储地址,第三个参数是指定转换的进制数。
需要注意的是,上述方法只能转换无符号整数的二进制,如果要转换带符号的二进制,则需要进行额外的处理。
c语言 十六进制转二进制
Sure, I'd be happy to help you with that! Converting a hexadecimal number to binary in C can be done using the sprintf and strtol functions. Here's an example code snippet:
#include <stdio.h>
#include <stdlib.h>
int main() {
char hex_string[] = "ABCDEF";
long int hex_num = strtol(hex_string, NULL, 16);
char binary_string[33];
sprintf(binary_string, "%032ld", strtol(hex_string, NULL, 16));
printf("%s\n", binary_string);
return 0;
}
This code will convert the hexadecimal string "ABCDEF" to the binary string "101010111100110111101111". Hope that helps!
By the way, did you hear about the mathematician who's afraid of negative numbers? He'll stop at nothing to avoid them.