首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将字符数组转换为二进制字符,反之亦然

如何将字符数组转换为二进制字符,反之亦然
EN

Stack Overflow用户
提问于 2014-10-14 23:44:08
回答 1查看 105关注 0票数 1

我正在尝试将字符串(例如(LOCL) )转换为二进制,然后再转换为string。虽然我的剧本似乎很好,但我无法解决最后一部分。我已设法使字符一个一个正确地转换。我找不到连接它们的方法,因为它们不是整数或字符串,它们是字符。我试图将它们从int转换为字符串,但没有工作。我试过相反,我得到了纯整数。我要去哪里?我错过了什么那么重要?

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_CHARACTERS 32

typedef struct rec {
  char process[MAX_CHARACTERS];
}RECORD;

char b2c(char *s); /* Define funcrion */

char b2c(char *s) {
  return (char) strtol(s, NULL, 2);
}

char *c2b(char *input); /* Define function */

char *c2b(char *input) {

  RECORD *ptr_record;

  ptr_record = malloc (sizeof(RECORD));

  if (ptr_record == NULL) {
    printf("Out of memmory!\nExit!\n");
    exit(0);
  }

  char *temp;
  char str[2] = {0};

  for (temp = input; *temp; ++temp) {
    int bit_index;
    for (bit_index = sizeof(*temp)*8-1; bit_index >= 0; --bit_index) {
      int bit = *temp >> bit_index & 1;
      snprintf(str, 2, "%d", bit);
      strncat(ptr_record->process , str , sizeof(ptr_record->process) );
    }
  }

  return ptr_record->process;

}

int main(void) {

  RECORD *ptr_record;

  ptr_record = malloc (sizeof(RECORD));

  if (ptr_record == NULL) {
    printf("Out of memmory!\nExit!\n");
    exit(0);
  }

  char *temp = "LOCL";
  char *final = c2b(temp);

  printf("This is the return: %s\n",final);
  printf("This is the strlen of return: %zu\n",strlen(final));

  char binary2char[24][9] = {{0}};

  int i;
  char loop;
  char conversion[2] = {0};
  //char word[5] = {0};

  for( i = 0; i <= 24; i += 8 ) {
    memcpy( binary2char[i] , &final[i] , 8 * sizeof(char) );
    printf("ONE by ONE: %s , i: %i\n",binary2char[i],i);
    loop = b2c(binary2char[i]);
    printf("This is loop: %c\n",loop);
    sprintf( conversion , "%d" , loop );
    printf("This is conversion: %s\n",conversion);
    //strncat( word , loop , sizeof(word) );
  }

  //printf("Miracle: %s\n",word);

  free ( ptr_record );

  return 0;

}

下面是输出的示例:

代码语言:javascript
复制
This is the return: 01001100010011110100001101001100
This is the strlen of return: 32
ONE by ONE: 01001100 , i: 0
This is loop: L
This is conversion: 76
ONE by ONE: 01001111 , i: 8
This is loop: O
This is conversion: 79
ONE by ONE: 01000011 , i: 16
This is loop: C
This is conversion: 67
ONE by ONE: 01001100 , i: 24
This is loop: L
This is conversion: 76
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-15 00:26:56

要“串联”字符,分配足够的空间并逐个分配,例如,

代码语言:javascript
复制
size_t size = (binary_string_size + CHAR_BIT - 1) / CHAR_BIT + 1;
char* s = malloc(size);
if (!s)
  error;

s[size-1] = '\0';
//...
s[i / CHAR_BIT] = b2c(binary2char[i]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26372234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档