简体   繁体   中英

splitting a 6 digit integer in C#

I have an 6digit integer, let's say "153060" that I'll like to split into

int a = 15 (first 2 digits),

int b = 30 (second 2 digits),

int c = 60 (third 2 digits),

The first thing that comes to mind is to convert the int to a string, split it using SubString (or a variation), and then convert back to an int.

This seems like a highly inefficient way to do it though. Can anyone recommend a better/faster way to tackle this?

Thanks!

Additional Info: the reason for splitting the int is because the 6-digit integer represents HHMMSS, and I'd like to use it to create a new DateTime instance:

DateTime myDateTime = new DateTime (Year, Month, Day, a , b, c);

However, the user-field can only accept integers.

int y = number / 10000;
int m = (number - y*10000) / 100;
in d = number % 100;

If your end goal is a DateTime , you could use TimeSpan.ParseExact to extract a TimeSpan from the string, then add it to a DateTime :

TimeSpan time = TimeSpan.ParseExact(time, "hhmmss", CultureInfo.InvariantCulture);
DateTime myDateTime = new DateTime(2011, 11, 2);
myDateTime = myDateTime.Add(time);

(Assumes >= .NET 4)

How about something like this?

int i = 153060;

int a = i / 10000;
int b = (i - (a * 10000)) / 100;
int c = (i - ((a * 10000) + (b * 100)));

You can do that without converting to string with:

int a = 153060 / 10000;
int b = (153060 / 100) % 100;
int c = 153060 % 100;

I am not sure about how efficient that is compared to converting to string. I think this is only 4 operations. So it might be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM