Click here to Skip to main content
15,886,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you convert from a string (that represents a decimal value) to a byte array?


Let says the users enter 1000 the program would produce {E8, 03, 00, 00}

And 1000000 will give {40, 42, 0F, 00}



Is there a function that does this? I remember that I saw something like this before but I can not remember where. Maybe I was day dreaming.

Anyway, thanks In advance thanks for the comments and help...
Posted
Comments
Sergey Alexandrovich Kryukov 9-May-12 16:32pm    
Does it have to be "decimal"? Why not int, uint, Int64, Uint64?
--SA

Those are two different goals: 1) serialize a general-case string; which can be done using System.Text.Encoding, and the result depends on the encoding used; if the encoding represents one of Unicode UTFs, all results will be different but equivalent, and the failure to use UTF can lead to data loss (think '????' characters); 2) serialization of a number represented by a string.

In the second case, it has nothing to do with string. You should work with data, not with the strings representing data. The strings can be used only for presentation of data in UI, human-readable files and the like.

Anyway, you can parse a string to any numeric type using their Parse or TryParse methods. For example:
http://msdn.microsoft.com/en-us/library/system.uint32.parse.aspx[^],
http://msdn.microsoft.com/en-us/library/system.uint32.tryparse.aspx[^].

(Please see other numeric types you might need.)

And then, you can serialize numeric value to array of bytes — and back. Please see the class System.BitConverter:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx[^].

—SA
 
Share this answer
 
v2
Comments
Maciej Los 10-May-12 8:16am    
Great answer, my 5!
By the way, thank you for accepting "connection" on LinkedIn site.
Sergey Alexandrovich Kryukov 10-May-12 12:38pm    
Thank you.
--SA
Member 8525993 14-May-12 9:36am    
SA

Thanks, I went with the second option.
Sergey Alexandrovich Kryukov 14-May-12 14:51pm    
You are welcome.
If so, please accept the answer formally (green button) -- thanks.
--SA
Could you use Conversion.Hex Method [^]
 
Share this answer
 
Are you thinking of the old Hex()[^] function?
 
Share this answer
 
Hi ,

to convert the string to byte array, u can use following function:

C#
byte[] array = System.Text.Encoding.ASCII.GetBytes(InputString);



Here,
InputString
is the user's input.


Also, following links may be useful for u:

http://www.chilkatsoft.com/faq/dotnetstrtobytes.html[^]

http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp[^]

http://www.dotnetperls.com/convert-string-byte-array[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900