C++ Integer to Char(Hex) problems

18 Feb 2012

Here is the part of the code im having problems with

int percent is passed in value 0-100

float endcalc = 0;
int end;

endcalc = (210*(percent/100))+10;
end = (int)endcalc;

display.putc(??); //?? must be in Hex format 0x00 

This is where im stuck I have tried everything I could google to try and figure this out myself but Im stumped. I get a value 0-100 do a calculation and get a value(I don't care about the loss of deciaml places in conversion to int). For a percent of 80 I need endcalc to be 178 and ?? to equal 0xB2. I have tried printf with %#X but I couldn't get it to work.

19 Feb 2012

Just tested your formula in excell, Works, but if you use putchar, with ox35 You should re I've the character '3' Anything less than 0x20, 32, is non printable.

Printf ..... %02x will print the NUMBER

I am guessing the # gets ignored, and not processed.

Hope this helps.

Ceri

19 Feb 2012

Umsae,

In addition to Ceri's comment about using "%02x" for the format string, you will have to watch out for integer truncation before any floating point calculation kicks in.

I.E. try -

endcalc = (210*(percent/100.0))+10;

Having the constant '100.0' (with the decimal point) inside the parenthesis is important to tell the compiler to start use floating point earlier.

20 Feb 2012

Umsae,

To display the value of 178, three calls to putc() would be necessary: putc('1'), putc('7'), and putc('8'). In hex these would be: putc(0x31), putc(0x37) and putc(0x38). The problem is you have to convert a value of 178, or B2h, into those three displayable characters. It's better to let printf() do that for you.

By the way, the ASCII codes for the numerals '0' to '9' are 30h to 39h. The uppercase alphabet starts 'A' at 41h, and the lowercase alphabet starts 'a' at 61h. And then there are punctuation and control codes. All of these occupy 00h to 7Fh, because the original ASCII had only seven bits. The paper tape used on teletype machines was about an inch wide and had tiny sprocket holes in the middle, with three slightly larger holes to the left of the sprocket holes and four holes to the right. It looked something like this:

<<tape>>
    | o o o . o o o o |
    |       .         |
    |   o o .       o |
    |   o o .   o o o |
    |   o o . o       |
    |       .         |
<</tape>>

When IBM came out with the PC, they realized that since a byte has eight bits, an 8-bit ASCII character set could have twice as many characters as a 7-bit ASCII character set. The characters from 80h to FFh were known as the extended character set. That is the range your value of B2h falls into.

20 Feb 2012

Thanks for all the help, by combination of the above it works now.