开发者

Assigning a value to variable

开发者 https://www.devze.com 2022-12-22 04:27 出处:网络
If I wanted to convert binary into decimal, is there way I could do this: Assuming: newState[i-2] = 0, newState[i-1] = 0,

If I wanted to convert binary into decimal, is there way I could do this:

Assuming:

newState[i-2] = 0,
newState[i-1] = 0,
newState[i] = 1

binary = newState[i开发者_JAVA百科-2], newState[i-1], newState[i]; // but if I did this, bin = 0, not 001.

I want to do this so I can pass binary into another method to convert into decimal.


You can use bit twiddling (this assumes that newState[N] is either 0 or 1):

binary = (newState[i-2] << 2) |
         (newState[i-1] << 1) |
         (newState[i]);


Your question is somewhat unclear. What exactly do you have? Do you have an array with elements holding the individual bits of your value? Then you need to compose the real value out of those bits, like

bit[0] = 0;
bit[1] = 0;
bit[2] = 1;
unsigned int value = (bit[0]) | (bit[1]<<1) | (bit[2]<<2);

Or do you have a value you want to display as binary? Then you need to convert from a value to a binary representation by extracting the individual bits and displaying the appropriate character. Unfortunately no binary presentation modifier is available for standard functions using format strings (as %x is for hexadecimal strings).

Or do you have a string represenation of a value in binary format? In this case you might want to look at strtoul, which can convert string representations of values to their value for a range of number bases, including the base 2.

In general, a number in C does not have a binary, hexadecimal or whatever format. A number is a number, and the only format it does have (apart from the representation on the real machine) is simply its length and whether it is signed or unsigned (I'm leaving out floating point numbers here). "Binary", "hexadecimal", "decimal" and the like are only representations of the same value for the reader -- i.e., the human. The value on the machine is absolutely identical regardless of that representation.

binary = newState[i-2], newState[i-1], newState[i]; // but if I did this, bin = 0, not 001.

This is an expression that uses the comma operator. You can't concatenate values or strings like that in C.


if you want to hold array of binary values you can use int for that. So you automatically get the number. getting the values is also easy to bet ith bit you call (x & (1 << i))

0

精彩评论

暂无评论...
验证码 换一张
取 消