Convert UInt16 to binary

G

Guest

Hi group,

Is there an easy way to convert a UInt16 value in to a string which presents
it in a binary format. I need a conversion with a fixed length.

so 6 must be presented as '0000000000000110'

Any help or code examples would be higly appreciated.

Thanks a lot in advance,

Bart
 
A

Arne Vajhøj

bart said:
Is there an easy way to convert a UInt16 value in to a string which
presents it in a binary format. I need a conversion with a fixed length.

so 6 must be presented as '0000000000000110'

Any help or code examples would be higly appreciated.

Try:

Convert.ToString(v, 2).PadLeft(16, '0')

Arne
 
J

Jeroen Mostert

Arne said:
Try:

Convert.ToString(v, 2).PadLeft(16, '0')
Boooo-ring. These may be more acceptable for the LINQ era:

new string(Enumerable.Range(0, 16).Reverse().Select(i => "01"[v >> i &
1]).ToArray())

Or

new string(Enumerable.Repeat(v, 16).Select((x, y) => "01"[x >> y &
1]).Reverse().ToArray())

Or

Enumerable.Repeat(v, 16).Aggregate("", (x, y) => "01"[y >> x.Length & 1] + x)

(I'm kidding, don't use these.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top