c - 如何向字符数组添加填充和换行符

标签 c string

所以我有一些代码,它采用表示字符串的 char 数组并将其转换为二进制格式 但是,我需要对其进行格式化,以便数组中的每个第 32 个字符都有新行字符。例如,对于字符串“abcde”,“abcd”将是一行,因为每个字符为 8 位。 那么下一行将是“e”,然后由于 e 只有 8 位,我需要添加另外 24 个字符“0”来表示空终止符。 所以它必须是

第一行:32个0和1代表'abcd' 第二行:8 个 0 和 1 代表“e”,然后是 24 个 0

///
/**
* Takes a string and converts it to a char array representing
* its binary format
**/
char* stringToBinary(char* s) {
    if(s == NULL) return 0; /* no input string */
    size_t len = strlen(s);
    ascii = malloc(len*8 + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
    ascii[0] = '\0';
    for(size_t i = 0; i < len; ++i) {
        char ch = s[i];
        for(int j = 7; j >= 0; --j){
            if(ch & (1 << j)) {
                strcat(ascii,"1");
            } else {
                strcat(ascii,"0");
            }
        }
    }
    return ascii;
}   
///

最佳答案

在循环中,检查i是否是4的倍数,并在写入位之前在输出字符串中插入换行符。异常(exception)情况是 i == 0,因为那是字符串的开头。

分配字符串时,需要计算其中有多少换行符,并考虑到末尾额外的 0 位。

我还更改了将位附加到字符串的循环,以便它直接分配给数组索引,而不是使用 strcat()strcat() 每次都必须搜索字符串以找到空终止符。

char* stringToBinary(char* s) {
    if(s == NULL) return 0; /* no input string */
    size_t len = strlen(s);
    int newlines = len / 4;
    int bits = len * 8;
    if (len % 4 != 0) {
        newlines++; // Need another newline after the excess characters
        bits += 32 - 8 * (len % 4); // round up to next multiple of 32 bits
    }

    ascii = malloc(bits + newlines + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
    int ascii_index = 0;
    for(size_t i = 0; i < len; ++i) {
        char ch = s[i];
        if (i % 4 == 0 && i != 0) {
            ascii[ascii_index++] = '\n';
        }
        for(int j = 7; j >= 0; --j){
            if(ch & (1 << j)) {
                ascii[ascii_index++] = '1';
            } else {
                ascii[ascii_index++] = '0';
            }
        }
    }
    // Add remaining 0 bits
    for (ascii_index < bits + newlines - 1; ascii_index++) {
        ascii[ascii_index++] = '0';
    }
    // Add final newline and null terminator
    ascii[ascii_index++] = '\n';
    ascii[ascii_index] = '\0';

    return ascii;
}

关于c - 如何向字符数组添加填充和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003595/

相关文章:

string - Scala在字符串中查找字符串的位置

c - C支持函数表达式吗?

c - 如何在c中的某个位置终止字符指针?

python - 如何用python中的数组值写入文件?

java - 如何从 HttpServletRequest 获取 URL 的一部分?

c# - 将各种日期时间格式转换为特定格式

c - 为什么不在这里释放 calloc() 的内存(YOLO)

c - 有没有办法仅使用 malloc 和自由函数来更改数组大小?

c - 我无法解决 "segmentation fault: 11"

c# - 在 C# 中安全地解析 XML