Append/Concat multiple ushort values

328 views Asked by At

I am working on C# application (.Net 4.0). At some situation I want to append the multiple ushort values as mentioned below

Ushort a = 123;
Ushort b = 045;
Ushort c = 607;
Ushort d = 008;

And I want the result as 12304560700.

Currently with below approach

var temp = Convert.ToString(a) + Convert.ToString(b) + Convert.ToString(c) + Convert.ToString(d);

I am getting the temp value as 123456078.

I do understand that because of ushort datatype it eliminate all the leading zero. But I am expecting the result as 12304560700.

I may have made the use of padleft method but the length and leading zero counts are not fix, so that option also doesn’t suits my requirement.

I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.

Thanks in advance.

4

There are 4 answers

2
themiurge On

You want all your numbers to be formatted using 3 digits, with leading zeros if needed. Looking at Standard Numeric Format Strings you get this:

var temp = a.ToString("D3") + b.ToString("D3") + ...
1
Hank On
int a = 123;
int b = 045;
int c = 607;
int d = 008;

why cant u do it this way? wont the result be what u want?

int temp = a.ToString() + b.ToString() + c.ToString() + d.Substring(d.Length - 2);

result as 12304560700.

1
Sweeper On

ushorts are not capable of storing numbers with leading zeros. In its eyes, 45 and 045 are the same exact number.

I recommend you to just store the numbers as strings, like this:

var a = "123";
var b = "045";
var c = "607";
var d = "008";

This is especially easy to do if you are getting these things from the console.

0
Jom George On

Instead of assigning values to ushort assign it to string or var.

eg: string a="123"; string b="011" etc or var a="123" etc

then var temp = a+b+... this will work. No Ushort value store data leading with Zero. Thank you