Encoding, decoding an integer to a char array

后端 未结 10 2283
借酒劲吻你
借酒劲吻你 2021-02-06 19:44

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array?

I was looking for an answer but didn\'t get a

10条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 20:19

    What you have will not work in the manner in which you have it. For example, a is 32 bit and in your example you the high order bits set, which means it cannot fit into a 4 digit number with your printf statement. (0xff00ffaa = 4278255530, which is more then 4 digits) I believe it will overflow the buffer. I believe printf will convert it and overflow the field, but it depend on how your compiler/C implements the printf function when there is not enough buffer space.

    For the printf statement you have, the maximum value you could pass in would be 9999 for 4 characters. Likewise, in you example of transferring the data with the 3 byte length field, you would have a maximum length of 999. In theory your length could be 1000, if you added 1 to the length, but the buffer you have declared, is 1024 where the maximum buffer length you would need would be 1004 bytes long.

    Using ASCII characters does make messages/data portable across the system, but it is at the expense of using more bandwidth/space and programming time and effort to convert back and forth from ASCII to transfer the data.

    It seems like you have a good idea, but it still needs a bit of work.

提交回复
热议问题