C鱼眼int转二进制并插入数字
时间: 2023-06-28 11:15:00 浏览: 53
以下是一个用 C 语言实现的将整数转换为二进制并插入数字的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int insert_number(int num1, int num2, int pos) {
// 将num1转换为二进制字符串
char binary_str[33];
itoa(num1, binary_str, 2);
// 将num2转换为二进制字符串
char binary_num2[33];
itoa(num2, binary_num2, 2);
// 在二进制字符串的指定位置插入num2
int binary_len = strlen(binary_str);
int num2_len = strlen(binary_num2);
char *temp_str = (char *)malloc(binary_len + num2_len + 1);
if (temp_str == NULL) {
printf("内存分配失败\n");
exit(1);
}
strncpy(temp_str, binary_str, pos);
strncpy(temp_str + pos, binary_num2, num2_len);
strncpy(temp_str + pos + num2_len, binary_str + pos, binary_len - pos);
temp_str[binary_len + num2_len] = '\0';
// 将二进制字符串转换为整数并返回
int result = strtol(temp_str, NULL, 2);
free(temp_str);
return result;
}
```
这个函数使用了 `itoa()` 函数将整数转换为二进制字符串,使用 `strncpy()` 函数将二进制字符串插入到指定位置,并使用 `strtol()` 函数将二进制字符串转换回整数。请注意,这个函数使用了动态内存分配来保存临时字符串,所以需要在函数结束后释放内存。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)