Simplest way to convert integer to char - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Simplest way to convert integer to char

blackr1234blackr1234 Posts: 31Member
Integer to char, the [b]simplest[/b][u][/u] way.

Like the str function: str(integer VAR, string VAR).
But I need integer VAR --> char VAR.

Example:
1 to '1'
123 to '123'
Also, -1 to '-1' if possible.

Anyone any idea, please?

Comments

  • _Atex__Atex_ Posts: 163Member
    : Integer to char, the [b]simplest[/b][u][/u] way.
    :
    : Like the str function: str(integer VAR, string VAR).
    : But I need integer VAR --> char VAR.
    :
    : Example:
    : 1 to '1'
    : 123 to '123'
    : Also, -1 to '-1' if possible.
    :
    : Anyone any idea, please?
    :

    You gotta use the [b]str[/b] procedure and process the resulting string, easy, since every string is an array of chars. Even if would be possible, you couldn't convert 123 or -1, only single digit positive integers. Here's a simple method:[code][color=Blue]var i,j:integer;
    s:string;
    ch:array[0..255] of char absolute s;
    { "ch" occupies the same place in memory as "s"}


    begin
    repeat
    write('Enter a value (0 to quit): ');readln(i);
    str(i,s);
    for j:=1 to byte(ch[0]) do { ch[0] is the length marker }
    writeln('ch[',j,']=',ch[j]);writeln;
    until i=0;
    end.[/color][/code]
  • blackr1234blackr1234 Posts: 31Member
    Thanks for reply, Atex.

    Question: As you have said only a single digit is possible, then how about chr(integer+48)?

    Please check your mailbox, I have mailed you a letter 2 days ago.

    Thanks v. much,
    blackr1234
  • _Atex__Atex_ Posts: 163Member

    :
    : Question: As you have said only a single digit is possible, then how
    : about chr(integer+48)?
    :

    [b]chr[/b] converts a value to a char type, it accepts a byte, so doesn't matter what you pass down to it, will only convert the lower 8bit of the argument.

    [b]str[/b] does the same thing but returns a string type, so for only 1 digit arguments returns a 1 length string which is a char ( although is stored as 2 bytes not 1 like a char).

Sign In or Register to comment.