Convert any object to a byte[]

Use the BinaryFormatter: byte[] ObjectToByteArray(object obj) { if(obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, obj); return ms.ToArray(); } } Note that obj and any properties/fields within obj (and so-on for all of their properties/fields) will all need to be tagged with the Serializable attribute … Read more

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is a fairly concise way to do this: static readonly string[] SizeSuffixes = { “bytes”, “KB”, “MB”, “GB”, “TB”, “PB”, “EB”, “ZB”, “YB” }; static string SizeSuffix(Int64 value, int decimalPlaces = 1) { if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException(“decimalPlaces”); } if (value < 0) { return “-” + SizeSuffix(-value, decimalPlaces); } if … Read more

How do I initialize a byte array in Java?

You can use an utility function to convert from the familiar hexa string to a byte[]. When used to define a final static constant, the performance cost is irrelevant. Since Java 17 There’s now java.util.HexFormat which lets you do byte[] CDRIVES = HexFormat.of().parseHex(“e04fd020ea3a6910a2d808002b30309d”); This utility class lets you specify a format which is handy if … Read more

How do I convert Long to byte[] and back in java

public byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public long bytesToLong(byte[] bytes) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(bytes); buffer.flip();//need flip return buffer.getLong(); } Or wrapped in a class to avoid repeatedly creating ByteBuffers: public class ByteUtils { private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); public static byte[] longToBytes(long x) { buffer.putLong(0, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)