开发者

I need to assign a variable with a 64-bit value

开发者 https://www.devze.com 2023-01-30 02:28 出处:网络
if i define a structure x1 and then assign an unsigned int xyz:64, it will create a 64 bit integerright?

if i define a structure x1 and then assign an unsigned int xyz:64, it will create a 64 bit integer right?

Now if i want to have all one's in the 64-bit, will the following work:

x1.xyz = 1

Will this value populate the variable with 64 one's? If there is any other way to define a varia开发者_Go百科ble and assign value to it, suggest me.

Please Help

Thanks in advance.


That will fill it with the bit pattern 000...001. The value that results in a 111...111 bit pattern is -1.


Doing it with a NOT operation (~) is probably the one with the least amount of typing:

unsigned int x = ~0 ;

However I'm not entirely sure if there is a way to ensure that this fills 64 bits without doing some kind of typecast, like this:

__int64 y = ~ (__int64)0 ;


Assigning 1 to x1.xyz will result in 63 bit of 0 and 1 bit of 1 which in hex is 0x0000000000000001 what you should do is this : x1.xyz = 0xFFFFFFFFFFFFFFFF


Trying to assign -1 to an unsigned integer will result in compiler warnings at best. You'll have to cast the -1 to the type you are trying to assign to.

The alternative is to explicitly specify the value as 0xFFFFFFFFFFFFFFFFU.


You should use the standard type for a 64 bit unsigned integer which is uint64_t i.e.

#include <stdint.h>

struct MyStruct
{
    uint64_t xyz;
};

// in the code somewhere

struct MyStruct x1;
x1.xyz = ~0;
// or
x1.xyz = 0xFFFFFFFFFFFFFFFF;


Nope

this will assign the one to the variable, in binary that would be:

0000000000000000000000000000000000000000000000000000000000000001

to assign all ones you'll have to use the maximum value for the unsigned type (which should be unsigned __int64 in c++)

I think that max value is

18,446,744,073,709,551,615

According to this: http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.80).aspx


It is implementation defined whether or not an int as a bitfield is signed or not. So first of all you should use signed or unsigned to specify this.

But then if you are always just interested in 64 bit (which may or may not be supported for bitfields by your compiler) you should definitively just use the types uint64_t (or int64_t) from "stdint.h". Using a bitfield makes not much sense to me, then.

If you don't have that, do a typedef for the apprioate 64 bit type on your platform that you may later easily replace or put into #ifdef clauses.

0

精彩评论

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