【问题标题】:How to convert an array of characters to binary and vice versa in c如何在c中将字符数组转换为二进制,反之亦然
【发布时间】:2014-10-15 08:26:56
【问题描述】:

我正在尝试转换字符串,例如(LOCL) 转换为二进制并返回到字符串。尽管我的脚本似乎运行良好,但我无法解决最后一部分。我已经成功地将字符一一正确地转换了。我找不到连接它们的方法,因为它们不是整数或字符串,它们是字符。我试图将它们从 int 转换为字符串,但没有奏效。我尝试了相反的方法,我得到了纯整数。我哪里错了?我错过了什么这么重要?

#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;

}

这是一个输出示例:

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

【问题讨论】:

  • 不要将不相关的代码放入问题中。尝试create minimal complete code example that demonstrates your issue。注意:您的代码中有多个不相关的问题:例如,char 右移(首先转换为无符号字符),不必要的sizeof(char)(它始终是一个),您可以使用@987654326 @ 而不是 8, RECORD?

标签: c multidimensional-array binary


【解决方案1】:

要“连接”字符,分配足够的空间并一一分配,例如,

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]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2012-03-10
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    相关资源
    最近更新 更多