Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to byte arrays?

Tags:

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...".

like image 855
Martin Avatar asked Dec 20 '10 15:12

Martin


People also ask

Can we convert string to byte array in Java?

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.

Is byte array same as string?

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.

How do you convert a hex string to a byte array?

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);


2 Answers

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.

like image 83
kindall Avatar answered Oct 07 '22 14:10

kindall


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] 
like image 31
Mark Tolonen Avatar answered Oct 07 '22 15:10

Mark Tolonen