Reputation: 82321
I have a string in my database that represents an image. It looks like this:
0x89504E470D0A1A0A0000000D49484452000000F00000014008020000000D8A66040....
<truncated for brevity>
When I load it in from the database it comes in as a byte[]. How can I convert the string value to a byte array myself. (I am trying to remove the db for some testing code.)
Upvotes: 0
Views: 1664
Reputation: 131676
It sounds like you're asking how to convert a string with a particular encoding to a byte array.
If so, it depends on how the string is encoded. For example, if you have a base64 encoded string, then you could get a byte array using:
asBytes = System.Text.Encoding.UTF8.GetBytes(someString);
If the encoding is hexadecimal (as it appears to be in your example) there's nothing built into the BCL, but you could use LINQ (just remove the 0x
at the head of the string first):
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length).
Where(x => 0 == x % 2).
Select(x => Convert.ToByte(hex.SubString(x,2), 16)).
ToArray();
}
Upvotes: 2
Reputation: 545588
String
in .NET means “text” – there’s a fundamental difference to a byte array and no 1:1 mapping exists (just as for other complex .NET types).
In particular, a string is encoded in an appropriate character encoding. As has already been posted, a given text can be decoded into a desired byte representation. In your particular case, it looks as though you’ve got a individual bytes represented as padded hexadecimal numbers, i.e. every byte is two characters wide:
int bytelength = (str.Length - 2) / 2;
byte[] result = new byte[byteLength]; // Take care of leading "0x"
for (int i = 0; i < byteLength; i++)
result[i] = Convert.ToByte(str.Substring(i * 2 + 2, 2), 16);
Upvotes: 1
Reputation: 887405
I believe you're actually trying to convert the hexadecimal number to a byte array.
If so, you can do it like this: (Remove the 0x
first)
var bytes = new byte[str.Length / 2];
for(int i = 0; i < str.Length; i += 2)
bytes[i / 2] = Convert.ToByte(str.Substring(i, 2), 16);
(Tested)
Upvotes: 2
Reputation: 1038770
class Program
{
static void Main()
{
byte[] bytes = StringToByteArray("89504E470D0A1A0A0000000D49484452000000");
}
public static byte[] StringToByteArray(string hex)
{
int length = hex.Length;
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
Upvotes: 3
Reputation: 180787
String to Byte Array Conversion in C#
http://www.chilkatsoft.com/faq/dotnetstrtobytes.html
Upvotes: 0
Reputation: 161773
If it comes in as a byte[]
, then it's not a string.
What is the column data type? Varbinary?
Upvotes: 1