Convert array of char[] to byte[] and vice versa? C++

前端 未结 4 843
谎友^
谎友^ 2020-12-31 07:12

What is the best way to convert an array of chars to bytes and vice versa?

Solution:

void CharToByte(char* chars, byte* bytes, unsigned int count){
          


        
4条回答
  •  無奈伤痛
    2020-12-31 07:34

    In almost every C++ implementation you'll come across, a char is exactly a byte an octet. This is not guaranteed by the C++ standard, but it's practically always the case. A char is always at least 8 bits large, and the exact number of bits is given by the preprocessor constant CHAR_BIT. Also, the sizeof() operator tells you the size of an object/type in terms of the number of chars, not the number of bytes octets, so if you were on some weird system with a 16-bit char and a 32-bit int, then sizeof(int) would be 2, not 4.

    EDIT: Replaced byte by octet. A char is guaranteed to be a byte by the C standard, but a byte is not guaranteed to be an octet, which is exactly 8 bits. If you've ever read any French technical literature, they always use 'octet' instead of 'byte', and they have kilooctets (KO), megaoctets (MO), etc. instead of kilbytes and megabytes.

提交回复
热议问题