将大于 255 的数字转换为字节变量
我理解字节的概念和声明变量以节省处理空间。我知道一个字节可以存储的最大值是 255。
我似乎无法解决当前的问题,希望有人能够教育我并帮助我解决这个问题。我没有太多使用字节操作的经验。
我收到了一个需要更新的项目,并被告知将数据传递到我的项目的服务将开始使用 2 字节来传输 ID,而不是之前的 1 字节,因为它们的参数已经增长。
该变量的当前声明是:
Dim bytvariable As Byte = 0
接受 2 字节值的新声明是什么?
其次,我如何才能将 2 字节值转换为整数?
例如,他们向我传递了这个值:0x138,它应该显示为 312。
提前谢谢您。
I understand the concept of bytes and declaring variables to save on processing space. I understand that the max value that can be stored in a byte is 255.
I cannot seem to wrap my head around my current issue and was hoping that someone would be able to educate me and help me solve this problem. I don't have much experience working with byte manipulation.
I was given a project to update and was told that the service that is passing data to my project would start using 2bytes to transfer the ID rather than the 1 byte previously as their parameters have grown.
The current declaration for the variable is:
Dim bytvariable As Byte = 0
What is the new declaration to accept a 2 byte value?
Secondly, how would I be able to convert that 2 byte value into an integer number?
Example, they are passing me this value: 0x138 and it is supposed to come out as 312.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是“原语”的摘要 " .NET 中的数据类型及其大小。
是的,Int16 可能就是您想要的。
通常,您会从流中读取二进制数据,或者从字节数组中获取它。
要将这些源转换为 Int16,您可以这样做:
在 C# 中:
在 VB.NET 中,它将是:(
我认为)
Here's a summary of the "primitive" datatypes in .NET, and their sizes.
Yes, an Int16 is probably what you want.
Often you'd be reading the binary data from a stream, or getting it from an array of bytes.
To convert from those sources into an Int16, you can do this:
in C#:
In VB.NET, it would be:
(I think)
从我的头脑中,我建议如果你坚持这样做(而不是仅仅传递一个整数),你可以使用一个字节数组,第一个索引保存第一个数字,第二个索引保存第二个数字。字节[0] = 123,字节[1] = 255;
然后将它们组合成一个字符串 ex。字符串连接数 = byte[0].ToString() + byte[1].ToString();然后解析它。 int ID = Int32.Parse(concatenatedNumber);
示例是 C# 语言,但我认为您应该明白了。不过,我肯定宁愿将其作为整数传递。
from the top of my head I'd suggest if you insist on doing it that way (instead of just passing an integer), you could use an array of byte, first index holding the first number and the second index the second ex. byte[0] = 123, byte[1] = 255;
then combine them into a string ex. string concatenatedNumber = byte[0].ToString() + byte[1].ToString(); then parse it ex. int ID = Int32.Parse(concatenatedNumber);
Examples are in C#, but I think you should get the idea. I would definitely rather just pass it as an integer though.
你可以试试这个:
You could try this: