英文:
Why results of bitwise left in Java and in C are different?
问题
在C语言中,当将128以上的数值转换成无符号字符(unsigned char)时,会导致截断(wrap around)现象,即结果会回到0。而在Java中,char类型是16位的,所以没有这种截断现象。如果你想在Java中获得类似C语言的结果,可以使用以下方法:
char x = (char) 128;
char y;
y = (char)(x << 1);
int ke = y & 0xFF; // 使用位掩码将高位截断,保留低8位
System.out.println(ke);
这将在Java中产生与C语言相似的输出结果。
英文:
I have a code in c :
unsigned char x = (char)128;
unsigned char y;
y = (x << 1);
int ye = (int) y;
printf("%d" , ye);
output = 0
I have a code in Java :
char x = (char) 128;
char y;
y = (char)(x << 1);
int ke = (char) y;
System.out.println(ke);
output = 256
if x = 1-127 in c and java are the same, but when 128 and above the results are different,
is there anything I can do for results in java like in C?
答案1
得分: 1
在C中,诸如'char'等基本类型的'width'和属性未定义:这取决于编译器和架构。
在Java中,它们都有明确定义。
在Java中,'char'是一个16位的无符号整数。大多数接受字符的方法将解释这个数字作为Unicode中的代码点(例如'System.out.println()':'System.out.println((char) 65);'打印的是'A',而不是65。
显然,在您的C代码中,'char'被定义为一个8位宽度的数据类型;在一个8位系统中,128左移1位等于0(它是256... 这是100 000 000 - 9位;第9位是溢出并被丢弃,得到0)。
Java没有任何表示无符号8位的数据类型。
您可以使用'int'并自己处理溢出规则。您还可以使用'byte',并处理在Java中,字节是有符号的(操作它们的方法倾向于以有符号方式解释位;位本身就是它们是什么,不关心我们人类可能认为它们意味着什么。它们既不是有符号的也不是无符号的)。
英文:
The 'width' and properties of basic types such as 'char' are undefined in C: It's up to the compiler and architecture.
In java they are all exactly defined.
In java, a char
is a 16-bit unsigned whole number. Most methods that take chars will interpret this number as a codepoint in unicode (such as System.out.println()
: `System.out.println((char) 65); prints 'A', not 65.
Evidently, in your C code, char
is defined as an 8-bit width data type; 128 shifted left by 1, in an 8 bit system, is 0. (it's 256.. which is 100 000 000 - 9 bits; the 9th bit is overflow and is discarded, giving you 0).
Java does not have any data type that represents unsigned 8-bit.
You can use int
and take care of the overflow rules yourself. You can also use byte
, and deal with the fact that in java, bytes are signed (methods that operate on them tend to interpret the bits in a signed fashion; bits themselves are what they are and care not for what us humans imagine they might mean. They are neither signed nor unsigned).
答案2
得分: 0
C 和 Java 中的 char
类型大小不同
- 在 C 中为 8 位(检查
sizeof(char)
) - 在 Java 中为 16 位(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
因此,移位后的位会消失,因此
- 在 C 中,
x = 128
的二进制表示为10000000
,x << 1
的结果为00000000
,因此x << 1
为0
- 在 Java 中,
x = 128
的二进制表示为0000000010000000
,x << 1
的结果为0000000100000000
,因此x << 1
为256
英文:
The size of char
is different in C and Java
- 8 bits in C (check
sizeof(char)
) - 16 bits in Java (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
The shift out bit would disappears, thus
- In C,
x = 128
is10000000
in binary,x << 1
results00000000
, thusx << 1
is0
- In Java,
x = 128
is0000000010000000
in binary,x << 1
results0000000100000000
, thusx << 1
is256
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论