Is there a function that returns the ASCII value of a character? (C++)

前端 未结 5 1090
生来不讨喜
生来不讨喜 2020-12-31 05:14

I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...

On a similar note, what is the function that converts between

相关标签:
5条回答
  • 2020-12-31 05:31
    char c;
    int ascii = (int) c;
    s2.data[j]=(char)count;
    

    A char is an integer, no need for conversion functions.

    Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?

    0 讨论(0)
  • 2020-12-31 05:36

    If you want to get the ASCII value of a character in your code, just put the character in quotes

    char c = 'a';
    
    0 讨论(0)
  • 2020-12-31 05:39

    You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:

    int x = 'A';  // x = 65
    int y = '\t'; // x = 9
    

    To convert a number to hexadecimal or decimal, you can use any of the members of the printf family:

    char buffer[32];  // make sure this is big enough!
    sprintf(buffer, "%d", 12345);  // decimal: buffer is assigned "12345"
    sprintf(buffer, "%x", 12345);  // hex: buffer is assigned "3039"
    

    There is no built-in function to convert to binary; you'll have to roll your own.

    0 讨论(0)
  • 2020-12-31 05:44

    As far as hex & binary - those are just representations of integers. What you probably want is something like printf("%d",n), and printf("%x",n) - the first prints the decimal, the second the hex version of the same number. Clarify what you are trying to do -

    0 讨论(0)
  • 2020-12-31 05:46

    You may be confusing internal representation with output. To see what value a character has:

    char c = 'A';
    cout << c << " has code " << int(c) << endl;
    

    Similarly fo hex valuwes - all numbers are hexadecimal numbers, so it's just a question of output:

    int n = 42;
    cout << n << " in hex is " << hex << n << endl;
    

    The "hex" in the output statement is a C++ manipulator. There are manipulators for hex and decimal (dec), but unfortunately not for binary.

    0 讨论(0)
提交回复
热议问题