Read a BigInteger serialized from Java into C# - c#

I have a BigInteger serialized to a file by a Java program using the writeObject method from ObjectOutputStream.
Can I deserialize it in C#? I tried using the java.math and java.io classes of vjslib, but I get an exception:
InvalidClassException
the class does not match the class of the persisted object for cl = java.lang.Number : __SUID = -8742448824652078965, getSUID(cl) = 3166984097235214156
Any ideas?

Do you have control over the serialization step from Java?
If so, I would suggest serializing a byte array, either as binary, or base64, and reading the byte array from the serialized structure.
Then you can pass the byte array to the System.Numerics.BigInteger constructor.

If you don't mind ugly hacks: I'd say the easiest (albeit not most efficient) way would be to just write it out as an ASCII String on the Java side, and parse that string on the C# side, instead of using binary de/serialization.

I suggest you don't use serialization for this, since the two versions of BigInteger are not compatible - they have different version ids.
You should write the object out in some other way, probably using the byte array from BigInteger.toByteArray
Reading this this question about serialization might also be insightful for you

Related

C# safe way to convert between bytes and other types

What is the safest way to guarantee that the following operation will be performed correctly:
When I read in 4 bytes as a uint32, I will write it out to a text file.
Later I will open this text file, read the number I wrote out previously, and then convert it back into the 4 bytes for use in other processing.
There is the BitConverter class to help you convert between primitive types and bytes.
Since you are storing this as a string, there isn't a whole lot to this. Obviously there is no issue converting the number into a string using .ToString(). So the only question I assume is how to go back in a reliable fashion. The solution is to use uint.Parse. i.e.:
var s = "12343632423432";
uint i = uint.Parse(s);
(PS: BitConverter is not helpful for conversion from strings)

create object with its property values from flat file, need implementation ideas

I got a flat file where the data is not delimetered or something else.
The file contains one large string and one row is represented by 180 chars.
Each column value is definied by a length of chars.
I have to create an object for each row, parse the 180 chars and fill
properties of the created object with the parsed values.
How can i solve this problem without permanent using substring or something else?
Maybe some nice solution with Linq?
Thanks a lot.
Solution 1 - Super fast but unsafe:
Create your class with [StructLayout(LayoutKind.Sequential)] and all other unmanaged code markings for length. Your strings will be char array but can be exposed as string after loading.
Read 180 bytes and create a byte array of the same size inside a fixed block
Change pointer to IntPtr and use Marshal.PtrToStructure() to load an onject of your class
Solution 2 - Loading logic in the class:
Create a constructor in your class that accepts byte[] and inside the objects using Covenrt.Toxxx or Encoding.ASCII.ToString() assuming it is ASCII
Read 180 bytes and create an object and pass it to .ctor
If you have to serialise back to byte[] then implement a ToByteArray() method and again use Covenrt.Toxxx or Encoding.ASCII.ToString() to write to byte.
Enhancement to solutions 2:
Create custom attributes and decorate your classes with those so that you can have a factory that reads metadata and inflates your objects using byte array for you. This is most useful if you have more than a couple of such classes.
Alternative to solutions 2:
You may pass stream instead of a byte array which is faster. Here you would use BinaryReader and BinaryWriter to read and write values. Strings however is a bit trick since it writes the length as well I think.
Use a StringReader to parse your text, then you won't have to use substring. Linq won't help you here.
I agree with OJ but even with StringReader you will still need the position of each individual value to parse it out of the string...there is nothing wrong with substring just make sure you use static constants when defining the begging and ending lengths. Example:
private static int VAR_START_INDEX = 0;
private static int VAR_END_INDEX = 4;
String data = "thisisthedata";
String var = data.Substring(VAR_START_INDEX,VAR_END_INDEX);
//var would then be equal to 'this'
This library can help you http://f2enum.codeplex.com/

Write Int array to Stream in .NET

what's the best way to write the binary representation of an int array (Int32[]) to a Stream?
Stream.Write only accepts byte[] as source and I would like to avoid converting/copying the array to an byte[] (array but instead streaming directly from the 'original location').
In a more system-oriented language (a.k.a. C++) I would simply cast the int array to a byte* but as far as I understood this isn't possible with C# (and moreover, casting byte* to byte[] wouldn't work out either way)
Thanks
Martin
PS: Actually, I would also like to stream single int values. Does using BinaryConverter.GetBytes() create a new byte array? In this case I extend my question to how to efficiently stream single int values ...
The simplest option would be to use BinaryWriter wrapping your output stream, and call Write(int) for each of your int values. If that doesn't use the right endianness for you, you could use EndianBinaryWriter from my MiscUtil library.
I don't know of anything built-in to do this more efficiently... I'd hope that the buffering within the stream would take care of it for the most part.
System.Array and System.Int32 both have the SerializableAttribute and so both support default serialization in a retrievable format.
http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx
There is sample code for Binary output and readback here:
http://msdn.microsoft.com/en-us/library/aa904194(VS.71).aspx

Reading Java UUID (from DB) in C#

I'm trying to map a table, where one of the column is a binary array (which is a Java UUID), to a C# class.
I would like to read the byte array and return a string representation of the UUID. Just wondering what's a good place to start.
If you've already got it as a byte array, then just call new Guid(bytes) to get a Guid; you can call ToString on that to convert it to a string if you particularly need to. (I'd suggest leaving it as a Guid though other than for diagnostics.)

C#: String -> MD5 -> Hex

in languages like PHP or Python there are convenient functions to turn an input string into an output string that is the HEXed representation of it.
I find it a very common and useful task (password storing and checking, checksum of file content..), but in .NET, as far as I know, you can only work on byte streams.
A function to do the work is easy to put on (eg http://blog.stevex.net/index.php/c-code-snippet-creating-an-md5-hash-string/), but I'd like to know if I'm missing something, using the wrong pattern or there is simply no such thing in .NET.
Thanks
The method you linked to seems right, a slightly different method is showed on the MSDN C# FAQ
A comment suggests you can use:
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5");
Yes you can only work with bytes (as far as I know). But you can turn those bytes easily into their hex representation by looping through them and doing something like:
myByte.ToString("x2");
And you can get the bytes that make up the string using:
System.Text.Encoding.UTF8.GetBytes(myString);
So it could be done in a couple lines.
One problem is with the very concept of "the HEXed representation of [a string]".
A string is a sequence of characters. How those characters are represented as individual bits depends on the encoding. The "native" encoding to .NET is UTF-16, but usually a more compact representation is achieved (while preserving the ability to encode any string) using UTF-8.
You can use Encoding.GetBytes to get the encoded version of a string once you've chosen an appropriate encoding - but the fact that there is that choice to make is the reason that there aren't many APIs which go straight from string to base64/hex or which perform encryption/hashing directly on strings. Any such APIs which do exist will almost certainly be doing the "encode to a byte array, perform appropriate binary operation, decode opaque binary data to hex/base64".
(That makes me wonder whether it wouldn't be worth writing a utility class which could take an encoding, a Func<byte[], byte[]> and an output format such as hex/base64 - that could represent an arbitrary binary operation applied to a string.)

Categories