Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting a 6 digit integer in C#

Tags:

c#

.net

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.

like image 277
Nicholas N Avatar asked Nov 02 '11 18:11

Nicholas N


3 Answers

int y = number / 10000;
int m = (number - y*10000) / 100;
in d = number % 100;
like image 135
Saeed Amiri Avatar answered Oct 24 '22 08:10

Saeed Amiri


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)

like image 18
Andrew Whitaker Avatar answered Oct 24 '22 09:10

Andrew Whitaker


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)));
like image 13
Derrick H Avatar answered Oct 24 '22 10:10

Derrick H