473,398 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Convert from string to byte[]

Hi,

I have the following binary data:

StringData = 800006000000;

which is equivalent to the following:

byte[] bytes = new byte[6];
bytes[0] = 0x80;
bytes[1] = 0x00;
bytes[2] = 0x06;
bytes[3] = 0x00;
bytes[4] = 0x00;
bytes[5] = 0x00;

How can I parse the string StringData to the equivalent byte array above?

I tried the following:
byte[] bytes = Encoding.ASCII.GetBytes(StringData);

but it gave me back garbage data.

This bytes[0] = 0x80; is equivalent to bytes[0] = 128;

Any help would be appreciated.

Thanks,

Yama

Nov 17 '05 #1
7 10794
Yama <Ya**@discussions.microsoft.com> wrote:
I have the following binary data:

StringData = 800006000000;

which is equivalent to the following:

byte[] bytes = new byte[6];
bytes[0] = 0x80;
bytes[1] = 0x00;
bytes[2] = 0x06;
bytes[3] = 0x00;
bytes[4] = 0x00;
bytes[5] = 0x00;

How can I parse the string StringData to the equivalent byte array above?

I tried the following:
byte[] bytes = Encoding.ASCII.GetBytes(StringData);

but it gave me back garbage data.


No, it gave you back exactly what you asked for - but that's not what
you wanted.

I suggest you call byte.Parse repeatedly with 2-character substrings,
specifying NumberStyles.AllowHexSpecifier.

Alternatively, you could use something like this:

static int ParseHexDigit(char c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'a' && c <= 'f')
{
return c-'a'+10;
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
throw new ArgumentException ("Invalid hex character");
}

public static string ParseHex(string hex)
{
char[] result = new char[hex.Length/2];

int hexIndex=0;
for (int i=0; i < result.Length; i++)
{
result[i] = (char)(ParseHexDigit(hex[hexIndex++])*16+
ParseHexDigit(hex[hexIndex++]));
}
return new string (result);
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Hi Yama,

You can convert from a string to a byte array using the
Convert.FromBase64String method.

Cheers,
Steve Goodyear
Vancouver, Canada
Nov 17 '05 #3
Your problem description still isn't 100% clear, but here's what I'm
assuming.

You have a string of digits (and possibly letters A-F or a-f) that
represent hexadecimal nibble values:

string StringData = "800006000000";

You want to translate this into a byte array, where each character from
the string becomes half of a byte (a nibble).

I don't think that there are any built-in classes in .NET to do this
for you. You'll have to do it yourself:

byte[] bytes = new byte[StringData.Length / 2];
for (int i = 0; i < StringData.Length - 1; i += 2)
{
int j = i / 2;
byte[j] = (ToNibble(StringData[i]) << 4) + ToNibble(StringData[i +
1];
}

private byte ToNibble(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else if ('a' <= c && c <= 'f')
{
return c - 'f';
}
else if ('A' <= c && c <= 'F')
{
return c - 'F';
}
else
{
throw new ArgumentException(String.Format("Character '{0}'
cannot be translated to a hexadecimal value because it is not one of
0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,A,B,C,D,E,F", c));
}
}

Nov 17 '05 #4
That does not work. I get an exception telling me Invalid length for a
Base-64 string.

"Steve Goodyear" wrote:
Hi Yama,

You can convert from a string to a byte array using the
Convert.FromBase64String method.

Cheers,
Steve Goodyear
Vancouver, Canada

Nov 17 '05 #5
Thanks to all my problem has been resolved with your help!

"Bruce Wood" wrote:
Your problem description still isn't 100% clear, but here's what I'm
assuming.

You have a string of digits (and possibly letters A-F or a-f) that
represent hexadecimal nibble values:

string StringData = "800006000000";

You want to translate this into a byte array, where each character from
the string becomes half of a byte (a nibble).

I don't think that there are any built-in classes in .NET to do this
for you. You'll have to do it yourself:

byte[] bytes = new byte[StringData.Length / 2];
for (int i = 0; i < StringData.Length - 1; i += 2)
{
int j = i / 2;
byte[j] = (ToNibble(StringData[i]) << 4) + ToNibble(StringData[i +
1];
}

private byte ToNibble(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else if ('a' <= c && c <= 'f')
{
return c - 'f';
}
else if ('A' <= c && c <= 'F')
{
return c - 'F';
}
else
{
throw new ArgumentException(String.Format("Character '{0}'
cannot be translated to a hexadecimal value because it is not one of
0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,A,B,C,D,E,F", c));
}
}

Nov 17 '05 #6
Bugs in my code sample:

The line

return c - 'f';

should read

return c - 'a';

The line

return c - 'F';

should read

return c - 'A';

Nov 17 '05 #7
Bugs in my posted code. The line

return c - 'f';

should read

return c - 'a' + 10;

The line

return c - 'F'

should read

return c - 'A' + 10;

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Nathan | last post by:
Is there a way to convert a string to a CipherMessage? I am calling a function that decrypts a CipherMessage and returns the value. The only problem is when I want to use an encrypted value stored...
1
by: Swarup | last post by:
I am reading a file (txt, xml, gif, ico, bmp etc) byte by byte and filling it into a byte arry. Now i have to convert it into a string to store it in the database. I use...
6
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that...
4
by: dale zhang | last post by:
Hi, I am trying to save and read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp Right now, I saved images without any...
25
by: Charles Law | last post by:
I thought this was going to be straight forward, given the wealth of conversion functions in .NET, but it is proving more convoluted than imagined. Given the following <code> Dim ba(1) As...
6
by: moondaddy | last post by:
I'm writing an app in vb.net 1.1 and need to convert a byte array into a string, and then from a string back to a byte array. for example Private mByte() as New Byte(4){11,22,33,44} Now how...
6
by: Bob Altman | last post by:
Hi all, I'm looking for the fastest way to convert an array of bytes to String. I also need to convert a String back to its original Byte() representation. Convert.ToBase64String and...
12
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} ...
19
by: est | last post by:
From python manual str( ) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.