Convert C++ byte array to a C string

前端 未结 3 440
北海茫月
北海茫月 2021-01-24 01:34

I\'m trying to convert a byte array to a string in C but I can\'t quite figure it out.

I have an example of what works for me in C++ but I need to convert it to C.

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-24 02:27

    Strings in C are byte arrays which are zero-terminated. So all you need to do is copy the array into a new buffer with sufficient space for a trailing zero byte:

    #include 
    #include 
    
    typedef unsigned char BYTE;
    
    int main() {
        BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
        char str[(sizeof byteArray) + 1];
        memcpy(str, byteArray, sizeof byteArray);
        str[sizeof byteArray] = 0; // Null termination.
        printf("%s\n", str);
    }
    

提交回复
热议问题