1

This might sound odd, but my issue is that I have a text string of hex values from a text file, like so:

"0x0f, 0x40, 0xff, ...."

I have stored them in an array split by the delimiters, but what I now need to do is have a byte array of what thay are in hex:

stringArray[0] = "0x0f";

byteArray[0] = 0x0f;

How do I do this (the user can load the text file, so I don't know what the values are), is there some sort of arithmetic I can use?

2
  • The question itself is valid in my opinion. Closing won't make him accept more answers, I guess. user646265: Please accept more answers that helped you. This will make more people want to help you. Commented Apr 13, 2011 at 10:02
  • 1
    Yes, I would have done, but I only just got above the 15 reputation that you need to accept answers. I will do so in future, now I am at 16 points. Commented Apr 13, 2011 at 12:15

3 Answers 3

3

If your string is in the correct format you can create your array using this code (will throw exceptions if the input is badly formatted):

var text = "0x0f, 0x40, 0xff";
var bytes = text
  .Split(new[] { ", " }, StringSplitOptions.None)
  .Select(s => (Byte) Int32.Parse(s.Substring(2), AllowHexSpecifier));
Sign up to request clarification or add additional context in comments.

Comments

2

You just have to parse each string. Because each one is already only one value, you can do this:

byte b;
if (byte.TryParse(s, NumberStyles.HexNumber, 
    CultureInfo.InvariantCulture.NumberFormat, out b)) 
{
    // b contains the value.
}

where s is the string you want to parse, and b is the resulting value.

2 Comments

Thanks. When I get enough reputation points, I'll vote up your answer.
I'll add that sadly the response is wrong. byte.TryParse doesn't support the 0x format. Read it here HexNumber Indicates that the AllowLeadingWhite, AllowTrailingWhite, and AllowHexSpecifier styles are used and AllowHexSpecifier Strings that are parsed using this style cannot be prefixed with "0x" or "&h"
0

Non of Odd hex string is correct. Check source from you get this string . It is because of truncation of string due to limit no of characters. If String is image is stored in database then retrieve it using program not using any tools

I was having same problem with .net and MSSQL and by using webservice and Java Client

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.