简体   繁体   中英

how to dump a binary representation bytes to decimal string?

below is the hex dump function,but what i need is dec dump.

void DumpBytes(unsigned char* inputBytes,int inputBytesLength,char* ouputString)
{
    unsigned char const Hex[] = "01234567890abcdef";
    for (int i = 0; i < inputBytesLength; i++)  
    {
        unsigned char binByte = inputBytes[i];
        ouputString[2*i] = (Hex[(binByte & 0xf0) >> 4]);
        ouputString[2*i + 1] = (Hex[binByte & 0x0f]);
    }
}

so,how to dump bytes to decimal string instead of heximal string.thanks in advance!

Bytes neatly fit in 2 hexadecimal characters, but decimal can take upto 3 characters (0 - 255) and it's not so neat to store them in a string without spaces. You might just want to print it out directly with spaces:

for (int i = 0; i < inputBytesLength; i++)  
  cout << (int)inputBytes[i] << ' ';

If you do want to store them in a string though, it's definitely possible and is very similar to the existing code:

ouputString[3*i] = '0' + binByte / 100;
ouputString[3*i + 1] = '0' + (binByte / 10) % 10;
ouputString[3*i + 2] = '0' + binByte % 10;
void DumpBytes(unsigned char* inputBytes,int inputBytesLength,char* ouputString)
{
    for (int i = 0; i < inputBytesLength; i++)  
    {
      unsigned char binByte = inputBytes[i];
      ouputString[3*i + 2] = binByte % 10 +'0';
      binByte \= 10;
      ouputString[3*i + 1] = binByte % 10 +'0';
      binByte \= 10;
      ouputString[3*i] = binByte % 10 +'0';
    }
    ouputString[3*i] = 0;
}

Output string must be at least (3*inputBytesLength + 1) big

代替>> 4& 0x0f ,使用/ 10% 10两次。

I think you're looking for Base64 encoding.

This encoding/decoding algorithm is used by many major protocols such as HTTP and IMAP (email protocol) to convert binary data to something more, how to say it, transferable.
It will take your data and produce two-bytes representation of each of your given bytes, so consider that if you have space limits.

There are also nice answers about B64 such as this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM