如何将带符号整数值分配给字节. [英] How to assign Signed integer value to byte.

查看:110
本文介绍了如何将带符号整数值分配给字节.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Developer,
有人告诉我,
如何将带符号整数值分配给字节值.
我想将一个Java代码行迁移到C#
这是Java代码

Hello Developer,
Any body tell me,
hows signed integer value assigned to byte value.
I want to migrate one java code line to C#
This is java code

abyte3[l++] = (new Integer(i<<4 | j)).byteValue();



此Java行将带符号的整数分配给字节值,并存储在字节数组中.
我已经在c#中迁移了此代码.
我在c#中使用了这一行代码,



This java line assigned signed integer to byte value and store in byte array.
This code i have migrate in c#.
I used this line of code in c#,

abyte3[l++] = (byte)(i<<4 | j)



但这只会给出正确的输出,最大为0到255的值,而不是带负号的整数.
任何人都告诉我,c#中java .bytevalue()方法的替代方法.


问候,
Ravi



but this only give the correct output upto 0 to 255 value and not take negative signed integer.
Any body tell me, Alternative of java .bytevalue() method in c#.


Regards,
Ravi

推荐答案

您的代码段正确.不同之处在于Java中的字节是有符号的(-128至+127),而在C#/.Net中则是无符号的(0至255).在这两种情况下,它们都将包含相同的8位,这取决于您接下来要对它们进行什么处理,这可能会或可能不会造成影响. (例如,重建字符串,保存到文件,丢弃套接字以及字节流"的其他此类用法在两种方式中都相同.但是,除〜,&和|之外的所有涉及算术的事物都将不一样.)

如果该符号对您很重要,则应在.Net中使用sbyte而不是byte.
Your code snippet is correct. The difference is that byte in Java is signed (-128 to +127) and in C#/.Net it is unsigned (0 to 255). In both cases they will contain the same 8 bits, and depending on what you want to do with them next, this may or may not matter. (For example, reconstructing a string, saving to file, throwing down a socket and other such uses of a byte ''stream'' will work the same way in both. But anything involving arithmetic, other than ~, & and |, will be different.)

If the sign is important to you you should use sbyte, not byte, in .Net.


请查看System.BitConverter.GetBytes方法:
Look at the System.BitConverter.GetBytes method: MSDN[^]
You can then select the least signficant byte if that is what you need.


这篇关于如何将带符号整数值分配给字节.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆