【问题标题】:Convert words to binary values将字转换为二进制值
【发布时间】:2021-03-06 07:36:52
【问题描述】:

我需要将 单词 转换为 二进制 数字,垂直放置 (\n)。 我需要编写一个函数,它将执行此转换.. 下面是一个示例.. 你能帮帮我吗?

//main
char* text = "Hello, how are you?";
const int len = strlen(text);
bool bytes1[len+1][8];
encode_string(text, bytes1);
for(int j = 0; j <= len; j++){
    printf("%c: ", text[j]);
    for(int i = 0; i < 8; i++){
        printf("%d", bytes1[j][i]);
    }
    printf("\n");
}
// prints:
// H: 01001000
// e: 01100101
// l: 01101100
// l: 01101100
// o: 01101111
// ,: 00101100
//  : 00100000
// h: 01101000
// o: 01101111
// w: 01110111
//  : 00100000
// a: 01100001
// r: 01110010
// e: 01100101
//  : 00100000
// y: 01111001
// o: 01101111
// u: 01110101
// ?: 00111111
// : 00000000

//function
void encode_string(const char string[], bool bytes[strlen(string)+1][8]){

}

【问题讨论】:

  • 你的代码不起作用怎么办?
  • 关于 cmets 在下面的先前答案中:“好的,但是程序将使用这个样本(主要注入):...,我有这些错误”。我建议自己做一些工作......,并获得一个调试器。

标签: c string binary


【解决方案1】:

你可以使用这个:

转换每个字符:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>


int main(void){

    char* text = "Hello, how are you?";
    int len_size = strlen(text);

    for(int j = 0; j <= len_size; j++){
        printf("%c: ", text[j]);
        for( int i = 7; i >= 0; i-- ) {
            printf( "%d", ( text[j] >> i ) & 1 ? 1 : 0 );
        }
        printf("\n");
    }

    return 0;
}

您的功能的另一个选项:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

void encode_string(char string[], int len_size);

int main(void){

    char* text = "Hello, how are you?";
    int len_size = strlen(text);
    encode_string(text, len_size);
    return 0;
}

void encode_string(char string[], int len_size){
    for(int j = 0; j <= len_size; j++){
        printf("%c: ", string[j]);
        for( int i = 7; i >= 0; i-- ) {
            printf( "%d", ( string[j] >> i ) & 1 ? 1 : 0 );
        }
        printf("\n");
    }
}

我已经知道你的错误,你正在尝试发送到函数,而你没有发送正确的参数...

【讨论】:

  • @OnlyForFun 它对我有用,我会索引一个打印件
  • @OnlyForFun 您正在尝试分配一个函数mblen 而您不希望这样,请使用字符串的大小!它会起作用,然后用绿色复选标记问题,这样人们就不会因为解决这个问题而浪费更多时间
  • 我已经复制了你的代码,我有这个 1 错误,看下面:qr.c: In function ‘encode_string’: qr.c:76:21: error: ‘len’ undeclared (first use in this function); did you mean ‘mblen’? 76 | for(int j = 0; j &lt;= len; j++){ | ^~~ | mblen qr.c:76:21: note: each undeclared identifier is reported only once for each function it appears screen:ibb.co/n3yFk4m
  • @OnlyForFun 你声明它正确发送你的代码打印!就像你在 shell 中所做的那样
  • @OnlyForFun 或者如果你想把你所有的代码发送到这里:codeshare.io 并点击分享,然后把链接发给我,我会解决的!我认为这是一个愚蠢的问题,可能是函数/变量的错误声明。
猜你喜欢
  • 2012-10-05
  • 2017-07-15
  • 2021-02-24
  • 2019-02-02
  • 2020-10-19
  • 2021-10-30
  • 2014-11-07
相关资源
最近更新 更多