For Programmers: Free Programming Magazines  


Home > Archive > C# > January 2006 > Convert string to byte array









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Convert string to byte array
hc

2006-01-24, 7:02 pm

Hi there,
Is it possible to turn a string into a byte array without using
encoding.
The string looks like "4D5A1C04" only it is a lot longer.
Are there any methods that will allow me to pass this into a byte[] so
that:
byte[] myBytes; can be populated as so

myBytes[0]=4D
myBytes[1]=5A
myBytes[2]=1C
myBytes[3]=04

etc..., or if the decimal values are passed into the byte array such
as:

myBytes[0]=77
myBytes[1]=90
myBytes[2]=28
myBytes[3]=04

etc...

I have tried different methods but am not able to get it to populate
the byte[] the way I need it to.
ie using methods shown on this page

http://www.dotnet247.com/247reference/msgs/2/12315.aspx

Cheers for your help.

Bruce Wood

2006-01-24, 7:02 pm

No, you have to write you own.

byte[] bArray = new byte[hexString.Length / 2];
bIndex = 0;
for (int i = 1; i < hexString.Length; i += 2)
{
byte b = HexDigitToValue(hexString[i - 1]);
b *= 16;
b = HexDigitToValue(hexString[i]);
bArray[bIndex] = b;
bIndex += 1;
}

where

private byte HexDigitToValue(char c)
{
switch (c)
{
case '1': return (byte)1;
case '2': return (byte)2;
...
case 'F':
case 'f':
return (byte)15;
case '0':
default:
return (byte)0;
}
}

hc

2006-01-25, 7:57 am

Cheers for the reply bruce,
I had another quick browse on the internet and found that if I send in
two characters
(ie 4D) then I can split them up and multiply the first one by 16 and
the second one by 1 and add them together this will give me the decimal
value for it.

eg, (16 * 4) + (1 * D(13)) = 64 + 13 = 77.

Again thanks for replying.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com