How can I convert a string to its byte value? I have a string "hello"
and I want to change is to something like "/x68..."
.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.
Since bytes is the binary data while String is character data. It is important to know the original encoding of the text from which the byte array has created. When we use a different character encoding, we do not get the original string back.
To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);
Python 2.6 and later have a bytearray type which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes "in place" rather than having to create a whole new string. It has a nice mix of the features of lists and strings. And it also makes your intent clear, that you are working with arbitrary bytes rather than text.
Perhaps you want this (Python 2):
>>> map(ord,'hello') [104, 101, 108, 108, 111]
For a Unicode string this would return Unicode code points:
>>> map(ord,u'Hello, 马克') [72, 101, 108, 108, 111, 44, 32, 39532, 20811]
But encode it to get byte values for the encoding:
>>> map(ord,u'Hello, 马克'.encode('chinese')) [72, 101, 108, 108, 111, 44, 32, 194, 237, 191, 203] >>> map(ord,u'Hello, 马克'.encode('utf8')) [72, 101, 108, 108, 111, 44, 32, 233, 169, 172, 229, 133, 139]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With