开发者

char to hex stream output in C++ using GCC 4.2.1

I have looked at this answer and can't get it to work for my situation. Please don't mark this as a duplicate as I can't get any of those answers to satisfy my situation.

I am mallocing some memory and copying data into that memory. I want to be able to print out the values of each of the bytes in hex in the format 0xFF where a byte equals 255.

I have cast my void* pointer to the memory as char* and am iterating the block of memory, but when I try and print out the values I get very wide output instead of two digits I get the full width of the unsigned int.

std::ostream& operator << (std::ostream &os, const Binary &obj)
{
    char* aschar = (char*) obj.buffer;
    for (long i = 0; i < obj.size; i++) 
    {
        if (isprint(aschar[i])) 
        {
            os << aschar[i];
        }
        else 
        {
            os << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int> (aschar[i]);
        }
    }
    return os;
}

I am memseting all the bytes to 128 in my test case. And all what I get back is ffffff80 when I am expecting 80. I am sure it has something to do with the casting and what not bu开发者_运维百科t I can't figure out how to express this the way I want it to.

I have also tried using sprintf and I can't get it to behave the way I want it to either. I am using Xcode 3.2.5 64 bit with GCC 4.2.1 if it matters.


Use unsigned char *aschar instead of (signed) char *aschar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜