I have a value stored in a short int that only makes sense when represented as hexadecimal digits with a decimal point. To exemplify: if the short int contains 1132 decimal (534h), then I need to output "5.34". The value comes from a function hidden in a shared library from a company, so I have to accept what I'm given. The result does not need to be a number type (int or float); rather, it can be of any type (e.g. string) that I can feed into the standard output stream.

The given value in the short int will always be such that when represented as hexadecimal digits, all digits will be in the range 0–9 (never A–F). There should always be two decimal places.

I know I can represent the decimal digits as hex digits with std::hex and output "534" with std::out, but I don't know how to store those individual digits (5, 3, 4) in memory so I can insert a . in them.

Once I do get the hex digits, should I convert the set of hex digits to a string and place the decimal point three characters from the right? Or would it be easier to somehow convert to a floating point format and divide by 100 (64h)?

有帮助吗?

解决方案

int dodgy(char* buf, unsigned input) {
    return sprintf(buf, "%x.%02x", input/256, input&0xff);
}
string dodgy2(unsigned input) {
    char buf[(CHAR_BIT * sizeof input + 11)/4];
    dodgy(buf, input);
    return string(buf);
}

其他提示

Hex is a print representation, not a value type. It sounds like BCD to me, in which case it all makes sense. You just have to convert it to decimal, nibble-wise, i.e. 4 bits at a time, and insert the decimal point before the last two digits. There's plenty of BDC to ASCII code around, and it's not hard to figure out yourself. The important thing is to figure out what it actually is first.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top