Lukali
Lukali

Reputation: 343

How to store the value of a char*?

I found the following code for converting an int/char to binary:

char* int2bin(int value, char* buffer, int bufferSize) {
    char *nextChar = buffer + bufferSize-1;            // location to write the least significant bit

    *nextChar = 0;  // add the null terminator

    do {
        nextChar--;
        (value & 1) ? *nextChar  = '1' : *nextChar  = '0'; // if set set to '1' else '0'
        value = value>>1;
        if (nextChar == buffer)
          break;
    } while (value);
    return nextChar;
 }

I know I can do the following

 binString = int2bin(inputBuff[i], binaryBuffer, 17);
 fprintf (WriteTo, "%s\n", binString);

But I would like to now store the char I just got into the binString, one of the binary bits of the conversion, in a char array which I want to pass on elsewhere, but my lack of understanding pointers has made it difficult to know how to get it.

I tried to do this by declaring a char array and trying to store the bit:

char inputBuffStr[32];

and then...

binString = int2bin(inputBuff[i], binaryBuffer, 17);
inputBuffStr[i] = binString;

where i increases per bit as part of analysing the input, and binString is a char* type.

I get the error: A value of type "char *" cannot be assigned to an entity of type "char" "inputBuffStr[i] = binString;"

If someone could maybe explain how I'd get the actual 0 or 1 that is present within binString? I don't seem to be able to understand how I can do fprintf of the value, but not output it to my char array?

Upvotes: 0

Views: 1352

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

You just have to use strcpy, which copies a \0-terminated C-style string:

char inputBuffStr[32];
strcpy(inputBuffStr,binString);

BTW: your question has nothing to do with C++, so I changed the tag to C.

Upvotes: 1

Related Questions