我试图在C中将字符串转换为二进制。此函数必须返回一个字符串(char *),如“010010101”等。此外,我想打印返回的内容。我无法确定这段代码
char* stringToBinary(char* s)
{
if(s == NULL) return 0; /* no input string */
char *binary = malloc(sizeof(s)*8);
strcpy(binary,"");
char *ptr = s;
int i;
for(; *ptr != 0; ++ptr)
{
/* perform bitwise AND for every bit of the character */
for(i = 7; i >= 0; --i){
(*ptr & 1 << i) ? strcat(binary,"1") : strcat(binary,"0");
}
}
return binary;
}
答案 0 :(得分:1)
对输入没有任何假设,只需打印字节中的位:
-m(no)fused-madd
答案 1 :(得分:1)
你的代码似乎很好。你只是错误的金额。这里有更正:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* stringToBinary(char* s) {
if(s == NULL) return 0; /* no input string */
size_t len = strlen(s);
char *binary = malloc(len*8 + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
binary[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(binary,"1");
} else {
strcat(binary,"0");
}
}
}
return binary;
}
样品运行:
"asdf" => 01100001011100110110010001100110
"tester" => 011101000110010101110011011101000110010101110010
"Happy New Year" => 0100100001100001011100000111000001111001001000000100111001100101011101110010000001011001011001010110000101110010
答案 2 :(得分:-2)
我不编译,但我希望这会激励你 所以: 一个字符是8位。 XXXXXXXX 使用掩码比较每个位更容易,更快 XXXXXXXX &安培; 00000001 只有当第1位为1时才是真的。 接下来会的 XXXXXXXX &安培; 00000010
char * stringToBinary( char * s )
{
// Variables.
char * aux, *binary, mask;
int size, i, y;
if(s == NULL){
// If arg is null, nothing to do.
return NULL;
}
// Calculate the size of the str.
size= strlen(s);
// alloc the str that contain the answer.
binary= malloc( (size*8)+1 );
// If no memory, nothing to do.
if( binary == NULL ){
// No memory
return NULL;
}
// save a copy of the arg.
aux= s;
// for each char in the str arg.
for( i=0; i<size; i++ ){
// In each char to examinate, reset the mask.
mask= 0x0001;
// For each bit of a char.
for( y=0; y<8; y++ ){
// Compare each bit with the mask.
if( (*aux) & mask ){
// add 0 to the answer.
strcat(bynary,"1");
}else{
// add 1 to the answer.
strcat(bynary,"0");
}
// shit the mask 1 pos to left.
mask= mask<<1;
}
aux++
}
return binary;
}