开发者

Converting a string of numbers to a byte array, keeping their display value.

开发者 https://www.devze.com 2023-03-23 23:03 出处:网络
My application gets data from a hardware device which is represented as a string, EG XYZ*012. I split the string up so I get “012” which I need to convert to an array 开发者_StackOverflow中文版of by

My application gets data from a hardware device which is represented as a string, EG XYZ*012. I split the string up so I get “012” which I need to convert to an array 开发者_StackOverflow中文版of bytes.

The problem I have is that I want each digit to keep its value so the character “0” will be stored in a byte as 0 and character “1” will be stored in the byte as 1 etc. This is required because I need to work on the bits of the bytes. I’ve tried using the “GetBytes” command but it converts “0” into 48 which is not what I want.

Is there a command to do what I want or do I need to manually handle each character in the string separately in a loop?


The following will normalize text character numbers, to their byte number equivalents:

byte[] bytes = data.Select(c => (byte)(c - '0')).ToArray();


Yes, use a loop. You want a particualr conversion which is not standard:

string numString = "012";

var byteDigits = new byte[numString.Length];
for(int i = 0; i < byteDigits.Length; i++)
    byteDigits[i] = (byte)(numString[i] - '0')


string numString = "012";
var numChars = numString.ToCharArray();
var result = new byte[numChars.Length];

for (int i = 0; i < numChars.Length; i++)
{
   result[i] = System.Convert.ToByte(numChars[i]);
}


string s = "012";
byte[] bytes = s.Select(c => byte.Parse(c.ToString())).ToArray();


using System.Linq you can do this. This will also skip over non digits.

var sourceString="012";
var result = sourceString.Where(c=>c>='0' && c<='9').Select(c=>(byte)(c-'0')).ToArray();

or if you want invalid characters to just be 255 you could do

var result = sourceString.Select(c=> (c>='0' && c<='9') ? (byte)(c-'0') : 255).ToArray();


I am not sure if i understand as what you want to achieve, Is this

List<byte> lstint = byval.Select(c => Convert.ToByte(c.ToString())).ToList();

For a Byte array

byte[] bytarr = byval.Select(c => Convert.ToByte(c.ToString())).ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消