1

I'm creating a C# program that create a packet data. One of the data in the packet is the Date and Time of 4 bytes size. I did this:

 public byte[] convertDateTimetoHex4bytes(DateTime dt)
    {
        //Convert date time format 20091202041800
        string str = dt.ToString("yyyyMMddhhmmss");
        //Convert to Int32 
        Int32 decValue = Convert.ToInt32(str);
         //convert to bytes
        byte[] bytes = BitConverter.GetBytes(decValue);
        return bytes;
    }

However, it seems that I need to use 8 byte of data, since 32 bit is too small (error during run time). Anyone can help me, if there is any other smaller Date Time format with 4 bytes? or any other way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

The error is logical as, the given string value when converted to a number, is simply too big to be represented by Int32 and the extra information cannot be "shoved in".

20140616160000  -- requested number (i.e. DateTime for today)
    2147483647  -- maximum Int32 value (2^31-1)

A UNIX Timestamp might work as is [traditionally] 32-bits, but it only has second precision and a limited range of 1970~2038. See How to convert a Unix timestamp to DateTime and vice versa? if interested in this approach.

The timestamp results in a smaller numeric range because it doesn't have unused numbers around the different time components; e.g. with the original format, numbers in the union of the following formats are not used and thus "wasted":

yyyyMMddhhmm60-yyyyMMddhhmm99   -- these seconds will never be
yyyyMMddhh60ss-yyyyMMddhh99ss   -- these minutes will never be
yyyyMMdd25hhss-yyyyMMdd99hhss   -- these hours will never be
                                -- etc.
Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220