Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Saturday, March 31, 2012

string to byte array conversion

I've a string similiar to "A509DE5B" (Length == 8 ) where each 2 characters are 1 hex number. How to convert such string into array of bytes (Lenght == 4)? In C# please, it's important...Byte.Parse()?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystembyteclassparsetopic.asp
Hi LesioS!

I think you should try out something like this (I haven't tested it out myself, not sure if it works!!)


string sBytes = "A509DE5B";

Byte[] bytes = new Byte[(int)(sBytes.Length/2)];

int i = 0, j = 0;

while(i < sBytes.Length)
{
bytes[j] = Byte.Parse(str.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}

Maybe it would work..

Good luck!
Oh, sorry, there's lots of mistakes in the code earlier code.

I tested this, and it worked, so be my guest! :)


string sBytes = "A509DE5B";
int i=0, j=0;
Byte[] bytes = new Byte[(int)(sBytes.Length/2)];
while(i < str.Length)
{
bytes[j] = Byte.Parse(sBytes.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}


byte[] bytes = new byte[str.Length / 2];
for(int i = 0; i < str.Length / 2; i++)
bytes [i] = Byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber);

works fine... THX

But I wonder why there's no such function like ToCharArray for string object which produces byte array. In many cases functions from .NET Framework uses byte arrays, not char arrays :(

Try this:

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Good luck!

Newbie


I have tried this

System.Text.

ASCIIEncoding encoding =new System.Text.ASCIIEncoding();string queryStringKey =ConfigurationManager.AppSettings["queryStringKey"];byte[] key = encoding.GetBytes(queryStringKey);return key;

to achieve this

//byte[] Key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6 };

but it is not working. What am I not getting? Newbie

Wednesday, March 28, 2012

String.split to a 2d array?

I have a list of states and abbreviations that I want to be able to pull
into a 2d array to bind to a control. The list looks like this:

AL:Alabama,AK:Alaska,AZ:Arizona,...

So If I take the starting and split it on the comma, it gives me a 1d
array with XX:Name in each element. Is there any easy way (like split)
to do this into a 2d array, so I end up with:

aStates(0,0)="AL"
aStates(0,1)="Alabama"

and so on...

I know a number of ways I could code this up to make it work but I'm
wondering if there's a nice quick n' dirty way using split or something
similar. Thanks!

MattString.Split allows you to pass in more than one delimiter. Maybe what you
could do is to figure that all even indexes are the state code and all odd
indexes are the state name.

"MattB" <somedudeus@.yahoo.com> wrote in message
news:352b8dF4fa2viU1@.individual.net...
> I have a list of states and abbreviations that I want to be able to pull
> into a 2d array to bind to a control. The list looks like this:
> AL:Alabama,AK:Alaska,AZ:Arizona,...
> So If I take the starting and split it on the comma, it gives me a 1d
> array with XX:Name in each element. Is there any easy way (like split)
> to do this into a 2d array, so I end up with:
> aStates(0,0)="AL"
> aStates(0,1)="Alabama"
> and so on...
> I know a number of ways I could code this up to make it work but I'm
> wondering if there's a nice quick n' dirty way using split or something
> similar. Thanks!
> Matt
Thanks. I considered that but decided on making a DataTable, looping
through the first array from splitting on the comma, and splitting a
second time on the colon and loading the table row that way.
Works well, I just wanted to see if I was overlooking a really easy
shortcut.

Matt

Peter Rilling wrote:
> String.Split allows you to pass in more than one delimiter. Maybe what you
> could do is to figure that all even indexes are the state code and all odd
> indexes are the state name.
> "MattB" <somedudeus@.yahoo.com> wrote in message
> news:352b8dF4fa2viU1@.individual.net...
>>I have a list of states and abbreviations that I want to be able to pull
>>into a 2d array to bind to a control. The list looks like this:
>>
>>AL:Alabama,AK:Alaska,AZ:Arizona,...
>>
>>So If I take the starting and split it on the comma, it gives me a 1d
>>array with XX:Name in each element. Is there any easy way (like split)
>>to do this into a 2d array, so I end up with:
>>
>>aStates(0,0)="AL"
>>aStates(0,1)="Alabama"
>>
>>and so on...
>>
>>I know a number of ways I could code this up to make it work but I'm
>>wondering if there's a nice quick n' dirty way using split or something
>>similar. Thanks!
>>
>>Matt
>

Monday, March 26, 2012

String.split to a 2d array?

I have a list of states and abbreviations that I want to be able to pull
into a 2d array to bind to a control. The list looks like this:
AL:Alabama,AK:Alaska,AZ:Arizona,...
So If I take the starting and split it on the comma, it gives me a 1d
array with XX:Name in each element. Is there any easy way (like split)
to do this into a 2d array, so I end up with:
aStates(0,0)="AL"
aStates(0,1)="Alabama"
and so on...
I know a number of ways I could code this up to make it work but I'm
wondering if there's a nice quick n' dirty way using split or something
similar. Thanks!
MattString.Split allows you to pass in more than one delimiter. Maybe what you
could do is to figure that all even indexes are the state code and all odd
indexes are the state name.
"MattB" <somedudeus@.yahoo.com> wrote in message
news:352b8dF4fa2viU1@.individual.net...
> I have a list of states and abbreviations that I want to be able to pull
> into a 2d array to bind to a control. The list looks like this:
> AL:Alabama,AK:Alaska,AZ:Arizona,...
> So If I take the starting and split it on the comma, it gives me a 1d
> array with XX:Name in each element. Is there any easy way (like split)
> to do this into a 2d array, so I end up with:
> aStates(0,0)="AL"
> aStates(0,1)="Alabama"
> and so on...
> I know a number of ways I could code this up to make it work but I'm
> wondering if there's a nice quick n' dirty way using split or something
> similar. Thanks!
> Matt
Thanks. I considered that but decided on making a DataTable, looping
through the first array from splitting on the comma, and splitting a
second time on the colon and loading the table row that way.
Works well, I just wanted to see if I was overlooking a really easy
shortcut.
Matt
Peter Rilling wrote:
> String.Split allows you to pass in more than one delimiter. Maybe what yo
u
> could do is to figure that all even indexes are the state code and all odd
> indexes are the state name.
> "MattB" <somedudeus@.yahoo.com> wrote in message
> news:352b8dF4fa2viU1@.individual.net...
>
>
>

String.Split with multi character delimiter

The Split method of the String class takes an array of char as it's
parameter. Rather than declaring a String, you need to declare a char array,
and work with that. Example:

Dim delString As String = "#|#"
Dim del As Char() = delString.ToCharArray()

...

s = source.Split(del)

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"PCK" <anonymous@dotnet.itags.org.discussions.microsoft.com> wrote in message
news:3CCCD026-B1BB-4F2D-8DE2-7D3BD398127F@dotnet.itags.org.microsoft.com...
> Hi,
> I have a string that I would like split into a single dimension string
array. The source string has a multi character delimiter. It appears that
string.split(delimiter) only splits based on the first character of the
delimiter.
> For example:
> Dim s() As String
> Dim source As String
> Dim del As String
> del = "#!#"
> source = "ABC#!#DEF#!#GHI"
> s = source.Split(del)
> s(0) = "ABC"
> s(1) = "!"
> s(2) = "DEF"
> s(3) = "!"
> s(4) = "GHI"
> Where as I would like the following returned. Does anyone know of a built
in function to do this?
> s(0) = "ABC"
> s(1) = "DEF"
> s(2) = "GHI"
> Thanks.
> PCKKevin, thanks for the response

I had thought about that earlier. Actually what happens when you use a char array is that it splits based on any item in the array not on the concatenation of all items in the array

Do you have any other suggestions.
myString.Replace( "#!#", "!" ).Split ( "!" ); ?

Dan.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:3F0E32B3-4C65-4AA2-A1A2-110F0644FA6A@.microsoft.com...
Kevin, thanks for the response.

I had thought about that earlier. Actually what happens when you use a char
array is that it splits based on any item in the array not on the
concatenation of all items in the array.

Do you have any other suggestions.
> I had thought about that earlier. Actually what happens when you use a
char array is that it splits based on any item in the array not on the
concatenation of all items in the array.

Oops. Sorry. That's true. Well, you could always use the Visual Basic.Net
Split() method (function), which takes a string as an argument.
Alternatively, you could try Daniel's solution.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:3F0E32B3-4C65-4AA2-A1A2-110F0644FA6A@.microsoft.com...
> Kevin, thanks for the response.
> I had thought about that earlier. Actually what happens when you use a
char array is that it splits based on any item in the array not on the
concatenation of all items in the array.
> Do you have any other suggestions.
the problem is the split method is not intended for use with string
seperators, to do one that works properly, you'd have to write one yourself.

alternatively, if there is a character you know (think highly likely) will
NOT appear in your text, use the replace method to convert to that character
as a seperator, then split.

hope that helps.
Dan.

"PCK" <anonymous@.discussions.microsoft.com> wrote in message
news:A6A5A7D8-5BB1-46D7-BC35-ABD8DD55130E@.microsoft.com...
Dan, thanks for the response.

But what if the data was "ABC#!#D!EF#!#GHI"

That would split it out as

ABC
D
EF
GHI

versus

ABC
D!EF
GHI
The VB Split method is what I was looking for. Thanks for the help.

stringbuilder & javascript (escape characters for quotes?)

Hey,

Im trying to write a javascript array from .net. The values of the array will sometimes have single quotes in - therefore I need some way to process the quotes so that I can output the javascript in the correct way.

I have:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString() +"','"+ dr[1].ToString()+"','"+ dr[2].ToString() +"');\n");

However, this does not deal with the quotes. I tried:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString().Replace("'","\'") +"','"+ dr[1].ToString().Replace("'","\'") +"','"+ dr[2].ToString().Replace("'","\'") +"');\n");

This was to try and replace all single quotes with \' which is the javascript escape character.
However, the double quotes dont work because .net think I'm adding more code.

kind of like in original asp when you have to have multiple quotes to get in a single quote...you know what I mean :)

any help much appreciated,

PeteThe first code sample should do fine.. single quote isnt going to trip anything up. If you were wanting to use double quotes in your string-builder for javascript, you would have to escape them with \" .

Now, are you anticipating a single quote will be in your datareader columns that you are building the stringbuilder with? If so, replacethose values with \' instead of the whole stringbuilder.
Cheers Sharbel,

Trying that today.

Pete
Hold on :)

I am anticipating single quotes in the data columns. Example: " today it's the first day ... " etc etc.

I've tried putting the dataReader columns into strings then replacing single quotes with \' but that doesnt seem to work...

Pete
Hey,

completely by chance I found that backslash is an escape character for .net as well as javascript:

hence:


dr[4].ToString().Replace("'","\\'")

works fine

Cheers,

Pete
Hi Pete,

FYI, the slash isn't a ".NET" escape character, per se; it works in C# because C# shares a lot of common syntax with Javascript (and Java, and C++, and any other languages that descended from C in one form or another).

In VB.NET, you escape double quotes by repeating them, just like in old "Classic" ASP with VBScript (although if you used JScript for Classic ASP, you *would* need to use the slash to escape characters).

Cheers,

Strings and parsing and errors with split

Hi

I am fairly new to .NET. However, I am very experienced with ASP. Here is the error I am getting
Value of type '1-dimensional array of String' cannot be converted to 'String'.
I am trying the following:
Dim tot As String
tot=cmd3.executescalar()
tot = split(tot,",")
response.write (tot)
Does anyone have any ideas of how I can get the values "1,2,3" from the database (as a string), parse those into an array, and then have the database look up each value and bid the results to the page. I have the datagrid in place. At the moment, my code works with 1 variable from the database (like 12), but not multiples like "1,2,3". The numbers could be anything too - "12,17" or "1,4,5,7,33,46"
Any ideas are appreciated - I am stuck as of now.
Thanks
HBHey,

You are on the right track, but you need to declare tot as an array, as such:

Dim nbrs As String = cmd3.ExecuteScalar()
if (nbrs <> String.Empty) Then
Dim tot() As String = nbrs.split(","c)
'Loops through the entries in the array
for each strID As String in tot
Response.Write(strID & "<br>")
next
end if

Brian
Wow - thanks for the quick response - I will try it out today.
HB
There is still and error:
<code>
Dim tot() As String = nbrs.split(","c)
<code
The error is - Variable 'tot' hides a variable in an enclosing block.
Is this "c" suppose to be there? I also tried nbrs.split(tot,",") and it gave back the same error.
I think I am getting close. I also need to use each of the numbers from the array in a SQL statement to get information from the DB and bind it. So, there will be one column with 3 results from the array containing 3 elements.

Thanks
HB
c means convert "," to a char. In C#, you denote chars with ', which obviously you can't do in VB.NET.

I think it means you are using tot outside of the if statement block, which the object wouldn't exist. Could you post your entire code so I can verify?

Brian
Sure - here is the code - it's messy at the moment. What it is suppose to do is select a product from the main page and then publish the 3 chemicals which are used for the product. So, I am using a one to many relationship. The data is stored in the database as 1,2,3 and I must take the 1,2,3 and get product 1, then product 2, then product 3. I also need to get away from the scalar - it should be Reader after closer inspection.
<code>
<%@. Page Language="VB" Debug="True" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Collections" %>
<%@. Import Namespace="System.Data.SqlClient" %>
<%@. Import Namespace="System.Configuration.ConfigurationSettings" %>
<%@. Register TagPrefix="header" TagName="top" src="http://pics.10026.com/?src=header.ascx" %>
<%@. Register TagPrefix="footer" TagName="bottom" src="http://pics.10026.com/?src=footer.ascx" %>
<html>
<head>
<title></title>
<script language="VB" runat="server">
Sub Page_Load(Src As Object, E As EventArgs)
Dim Conn As SQLConnection
Dim Rdr,Rdr2 As SQLDataReader
Dim Q1,Q2,Q3,total,number,Names,stringSQL2,Word As string
Dim x As integer

Q2 = Request.QueryString("product")
Dim strConn As string = AppSettings("connect")

Dim stringSQL As string = "Select " & Q2 & " from menu_green"

Dim SQL as string="Select names1,names2,names3 from menu_green where C1='" & Q2 & "'"
SQL = SQL & "OR C2='" & Q2 & "'"
SQL = SQL & "OR C3='" & Q2 & "'"
Dim Conn2 as New SQLConnection(strConn)
Dim Cmd3 as New SQLCommand(SQL,Conn2)
Conn2.Open()
Dim tot As String
'litHowMany.text=cmd3.executescalar()
tot=cmd3.executescalar()
'Response.write ("" & tot)
'Conn2.Close()

Dim nbrs As String = cmd3.ExecuteScalar()
if (nbrs <> String.Empty) Then
Dim tot() As String = nbrs.split(","c)
'Loops through the entries in the array
for each strID As String in tot
Response.Write(strID & "<br>")
next
end if

stringSQL2 = "Select id,names from products where id='" & tot & "'"
Conn = New SQLConnection(strConn)
Dim Cmd2 As New SQLCommand(stringSQL2,Conn)
Conn.Open

'Dim myname As string
'myname = cmd2.executescalar()
'response.write ("" & myname & "<br>")

Rdr2 = Cmd2.ExecuteReader()
myproducts.datasource = Rdr2
myproducts.databind()
Conn.close

Conn = New SQLConnection(strConn)

Dim Cmd As New SQLCommand(stringSQL,Conn)
'Dim Cmd2 As New SQLCommand(stringSQL2,Conn)

Conn.Open
Rdr = Cmd.ExecuteReader()
mylist.datasource = Rdr
mylist.databind()
Conn.close

End Sub
</script>
<code
Thanks for any input

HB
One thing: You declared tot twice, once as a variable, once as an array.

Thursday, March 22, 2012

Structure/Array Question - Easy

I have a Structure and need to create array of Structures for example... How do I accomplish this?

Structure MyStruct

Dim Input1 As String

Dim Input2 As String

End Structure

dim t() as MyStruct

try this

Dim myarray(10)As MyStruct

(if you want the length of the array to be 10)


This is your Structure:

Structure myStruct
Dim Input1 As String
Dim Input2 As String
End Structure

if you want to have an array of your structure with a fix length... then you can do it as..

Dim t(10) As myStruct

if you want to have an array of your structure with dynamic length... i mean if you are not sure what is the length then... you can do it as...

Dim t1() As myStruct
Dim iRow As Integer = 0
While (True) '...an endless loop... just to show example...
ReDim Preserve t1(iRow)
t1(iRow) = New myStruct
t1(iRow).Input1 = ""
t1(iRow).Input2 = ""
iRow += 1
End While

hope it helps./.