我创建了一个基本的控制台应用程序来进行这样的测试
short val = 32767;
val++;
Console.WriteLine(val);
Run Code Online (Sandbox Code Playgroud)
这给了我-32768作为预期结果
short val = 32767;
val = val +1;
Console.WriteLine(val);
Run Code Online (Sandbox Code Playgroud)
但这给了我这个错误
错误1**无法将类型'int'隐式转换为'short'.存在显式转换(您是否错过了演员?)
我很好奇是什么导致了这个?
提前致谢,
所以我所拥有的是一个short []数组,它表示WAV文件的原始数据.这意味着它不包括通常包含的任何页眉或页脚信息.为了播放这个音频,我需要将它转换为某种类型的流,不幸的是,这个short []数组中的数据是Int16,并且许多值超过255,因此无法转换为字节并且无法转换为流.有谁知道我怎么能播放这个音频数据?
因此,我正在为在线游戏制作自己的网络协议,为了节省空间,每条消息(通过TCP发送)都被赋予一个短的2字节ID,从服务器发送到客户端的所有消息,反之亦然是字符串,如何只用2个字节(字符)将java中的short转换为字符串?
更新:我可能不清楚我想要什么...我希望能够将一个短的int转换为2个字符,这样我就可以通过网络以短字节格式发送短消息,只需2个字节.将其解码回另一侧的短片(在动作3中).
一个角色可以容纳256个可能的值吗?所以256*256 = 65,536这是无符号短整数的大小!
这是我到目前为止所得到的:
public static String toCode(int c){
if(c <= 255 ){
return Character.toString((char)c);
}else{
return null;
}
}
public static int fromCode(String c){
return ((int)c.charAt(0));//Return the character code of the send string, 1 char only
}
Run Code Online (Sandbox Code Playgroud)
这可以将一个int变成一个可以通过网络发送的单个字符,现在我只需要让它使用2个字符就可以做到最短.
假设我像20/30对象一样循环,或者在我处理较小数字的任何其他情况下,使用short而不是int是一个好习惯吗?
我的意思是为什么这不常见:
for(short i=0; i<x; i++)
Method(array[i]);
Run Code Online (Sandbox Code Playgroud)
是因为性能提升太低了吗?
谢谢
我不知道如何提出这个问题.但是,这两行代码之间有什么不同?
Set<Integer> a = new HashSet<Integer>();
for (int i = 0; i < 100; i++) {
a.add(i);
a.remove(i - 1);
}
System.out.println(a.size());
Run Code Online (Sandbox Code Playgroud)
我预计99将成为输出
输出为1
Set<Short> a = new HashSet<Short>();
for (Short i = 0; i < 100; i++) {
a.add(i);
a.remove(i - 1);
}
System.out.println(a.size());
Run Code Online (Sandbox Code Playgroud)
我预计99将成为输出
输出为100
我遇到了问题.从对象到短的转换不起作用.
在课堂上我有(juste an exemple):
public const uint message_ID = 110;
Run Code Online (Sandbox Code Playgroud)
在另一个类中,在构造函数中,我有:
Assembly asm = Assembly.GetAssembly(typeof(ProtocolTypeManager));
foreach (Type type in asm.GetTypes())
{
if (type.Namespace == null || !type.Namespace.StartsWith(typeof(MyClass).Namespace))
continue;
FieldInfo field = type.GetField("message_ID");
if (field != null)
{
short id = (short)(field.GetValue(type));
...
}
}
Run Code Online (Sandbox Code Playgroud)
我没有问题直到演员阵容.我的字段不是null,而field.GetValue(type)给了我好的对象(对象值= 110).
在某个地方,我读到从对象到int工作的拆箱,好吧,我试过了,但它仍然不起作用:
object id_object = field.GetValue(type);
int id_int = (int)id_object;
short id = (short)id_object;
Run Code Online (Sandbox Code Playgroud)
唯一的例外是这个:http://puu.sh/5d2jR.png(对不起法语.它说它是类型或强制转换错误).
有没有人有解决方案?
谢谢你,Veriditas.
当我寻找答案时,我得到的命中是指从short转换为int,从nullable转换为not-null.但是,我陷入了如何从"更大"类型int转换?到"小"型短?.
我能想到的唯一方法是编写一个这样的方法:
private short? GetShortyOrNada(int? input)
{
if(input == null)
return (short?)null;
return Convert.ToInt16(input.Value);
}
Run Code Online (Sandbox Code Playgroud)
不过,我希望在一行中做到这一点,因为它只在项目的整个代码库中完成了一个地方,并且不会有任何变化.
short x, y;
short z = ((short)x) + ((short)y);
Run Code Online (Sandbox Code Playgroud)
所以我理解在Java中,一个值在被添加时被认为是一个整数.这只是语言中的一个细微差别.然而,在这里,我已经铸造short的变量x和y它仍然给了我一个错误说,
无法从int转换为short