first one is sign bit. for 2 (10) first one is sign 1 so its negative number. 2's compliment of 10 you will get -2.
Why unsigned int value in c bit-field became signed value?
-
08-10-2022 - |
سؤال
#include <iostream>
#include <stdint.h>
struct Foo
{
int a : 2;
int b : 2;
int c : 2;
int d : 2;
};
int main()
{
Foo foo;
foo.d = 2;
std::cout << sizeof(foo) << std::endl;
std::cout << foo.d << std::endl;
return 0;
}
Using g++, the result turns to be 4 -2
, how could foo.d became -2?
المحلول 2
نصائح أخرى
int
is signed by default, so an int :2
has a range of -2 through 1. Use unsigned int :2
if you want to be able to store values 0 through 3 instead.
لا تنتمي إلى StackOverflow