Difference between revisions of "Code Snippet: Characters and Strings to ASCII Values"
From Coder Merlin
(Created page with "== Characters and Strings to ASCII Values == <syntaxhighlight lang="swift"> // Credit: // https://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-f...") |
(→Java) |
||
(3 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
= Characters and Strings to ASCII Values = | |||
== Swift == | |||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
// Credit: | // Credit: | ||
Line 28: | Line 30: | ||
print("Hello".ascii) | print("Hello".ascii) | ||
</syntaxhighlight> | |||
== Python == | |||
<syntaxhighlight lang="python"> | |||
# Single Character | |||
print(ord('H')) | |||
# Entire string | |||
print([ord(char) for char in "Hello"]) | |||
</syntaxhighlight> | |||
[https://stackoverflow.com/questions/227459/how-to-get-the-ascii-value-of-a-character Single Character] && [https://stackoverflow.com/questions/8452961/convert-string-to-ascii-value-python String] | |||
== Java == | |||
<syntaxhighlight lang="java"> | |||
char c = 'x'; // some character | |||
int asciiCode = (int) c; // it's that easy! | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 09:53, 13 January 2020
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Characters and Strings to ASCII Values[edit]
Swift[edit]
// Credit:
// https://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va
// https://stackoverflow.com/users/2303865/leo-dabus
// First, set up required extension for Character
extension Character {
var isAscii: Bool {
return unicodeScalars.first?.isASCII == true
}
var ascii: UInt32? {
return isAscii ? unicodeScalars.first?.value : nil
}
}
// Then, set up useful extension for Strings
extension StringProtocol {
var ascii: [UInt32] {
return compactMap { $0.ascii }
}
}
// Demonstrate obtaining the value for a single character
print("H".ascii)
// Demonstrate obtaining the value for a string
print("Hello".ascii)
Python[edit]
# Single Character
print(ord('H'))
# Entire string
print([ord(char) for char in "Hello"])
Java[edit]
char c = 'x'; // some character
int asciiCode = (int) c; // it's that easy!