Binary value

S

Shawn B.

Greetings,

I've been up and down google on this one and clearly I don't know what
search terms to use because I can't locate how to do this for binary values
(or hex)...

in C#, we can specify a floating value by saying 0.0f and a hex number by
saying x = 0xFF10 but how do we specify a binary constant? I thought it
might be something like x = %1010101; but I honestly can't figure out what
it might be or how to locate it in the help file since can't even locate the
ones I do know about (float, decimal, hex, etc).

Anyone know?


Thanks,
Shawn
 
M

Marc Gravell

You can't do it as a *literal*, but it can be done indirectly...

Example:

static readonly int MY_CONST = Convert.ToInt32("10010101", 2);

When the class initialiser fires MY_CONST will evaluate the string as
an integer, but it will only ever run this once, so you get similar
performance to a literal [except that it won't be pre-combined with
other "constant" values at the compiler].

Marc
 
D

Dave Sexton

Hi Marc,

Interesting, but it should be noted that hex is a more standardized
approach - I don't see "binary" strings too often ;)
 
M

Marc Gravell

Indeed, and I have *never* used this string approach myself... included in
the context that in some circumstance it *might* be useful to see the bits
directly. Actually I tend to just use integer literals myself. I'm so used
to the 2^n sequence that I can usually spot the bits, and if not "calc" is
just a keypress away (on an extended keyboard, at least ;-p)

Marc
 
D

Dave Sexton

Hi Marc,

Good point. In my experience, when I need to see the bits it's probably
because I'm using flags, so an Enum with FlagsAttribute could be useful (or
possibly BitArray or BitVector32 structures). I can't remember ever needing
to see the bits in a literal, however.
 
S

Shawn B.

Good point. In my experience, when I need to see the bits it's probably
because I'm using flags, so an Enum with FlagsAttribute could be useful
(or possibly BitArray or BitVector32 structures). I can't remember ever
needing to see the bits in a literal, however.

I'm using my values in an enumeration. I've decided to convert the binary
into hex and use hex literals. I wouldn't normally be attempting such a
thing, but I'm writing a CPU emulator at the opcode chart is listed binary
numbers instead of hex... simply becuase the instuction, bitflags,
conditinals, source and destination are all packed into a single 32-bit
value so they use binary in the opcode charts.

If anyone cares, its the 32-bit 8-Core CPU from parallax.

For now, I'm converted the binary into hex and is sufficient for my rather
simple needs.

Thanks,
Shawn
 

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