Polyglot CheatSheet - Type Conversions
Last Updated: 2023-07-19
Number to String
Java
To Decimal String
int i;
// append to an empty String
String s = "" + i;
// use String.valueOf
String s = String.valueOf(i);
// use <Number class>.toString();
Integer.toString(i);
Integer i;
String s = i.toString();
To Hex String
Integer.toHexString(20320);
// 4f60
To Binary String
Integer.toBinaryString(8);
// 1000
To Octal String
Integer.toOctalString(8);
// 10
String to Number
Java
// To Float
Float f = Float.valueOf(str);
// To primitive
float f = (Float.valueOf(str)).floatValue();
JavaScript
parseInt(str);
parseFloat(str);
PHP/Hack
$num = (int)$str;
String to List
Python
>>> '9'.split()
['9']
String to Char Array
Java
String str = "someString";
char[] charArray = str.toCharArray();
Join Array/List As String
Java
Join array:
String[] names = new String[]{"a", "b", "c"};
System.out.println(String.join(",", names));
//a,b,c
Join List:
List<String> names = Arrays.asList("a", "b", "c");
System.out.println(String.join(",", names));
//a,b,c
Manipulate list before joining:
List<String> names = Arrays.asList("a", "b", "c");
String joined = names.stream()
.map(String::toUpperCase)
.collect(Collectors.joining(","));
System.out.println(joined);
//A,B,C
Bytes and Integer
Python: bytes
and int
int
to bytes
>>> d = bytes([65, 66, 67])
>>> d
b'ABC'
bytes
to int
>>> list(b'ABC')
[65, 66, 67]
or
>>> b'ABC'[0]
65
>>> b'ABC'[1]
66
>>> b'ABC'[2]
67
Bytes and Hex
Python: bytes
and hex
Use .fromhex()
and .hex()
>>> hex(ord('A'))
'0x41'
>>> bytes.fromhex('41')
b'A'
>>> bytes.fromhex('41 42')
b'AB'
>>> bytes.fromhex('41 4243')
b'ABC'
>>> bytes.fromhex('414243')
b'ABC'
another example:
>>> str = "89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00"
>>> str
'89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00'
>>> bytes.fromhex(str)
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00'
bytes
to hex
>>> bytes([65, 66, 67])
b'ABC'
>>> bytes([65, 66, 67]).hex()
'414243'
String and Bytes
Go
myString := string(myBytes[:])
Python: str
and bytes
Use .encode()
and .decode()
>>> 'ABC'.encode()
b'ABC'
>>> b'ABC'.decode()
'ABC'
Number to Enum
C++
auto foo_enum = static_cast<Foo>(foo_number);