简体   繁体   English

如何将字符串转换为ushort []

[英]How to convert string to ushort[]

I have been scouring the web for a solution to the conversion problem I have been facing where I am required to write into the User Memory of a RF Tag. 我一直在网上搜寻转换问题的解决方案,我一直面临将其写入RF标签用户存储器的问题。 The API accepts an ushort[] . 该API接受ushort[] I have created an app that accepts ASCII inputs as a test field. 我创建了一个接受ASCII输入作为测试字段的应用。 For instance, if the user enters Hurrah , then I need that to be converted to ushort[] { 0x4875, 0x7272, 0x6168} . 例如,如果用户输入Hurrah ,那么我需要将其转换为ushort[] { 0x4875, 0x7272, 0x6168} Here is how far I have gotten with this: 这是我得到的结果:

    [TestMethod]
    public void AsciiToHexConversionTest()
    {
        IList<ushort> outputList = new List<ushort>();
        var inputStr = "Hurrah";
        IList<char> output = new List<char>();

        char[] values = inputStr.ToCharArray();
        foreach (char letter in values)
        {
            // Get the integral value of the character. 
            var value = Convert.ToInt32(letter);

            // Convert the decimal value to a hexadecimal value in string form. 
            // uncommenting this line results in an error, and I cant figure out how to convert int to hex without it being a string
            //output.Add(string.Format("{0:X}", value));

        }

        // use bitwise or to package two bytes to a ushort value
        for (int i = 0; i < output.ToArray().Length; i++)
        {
            outputList.Add((ushort)((output[i] << 8) | output[i + 1]));
        }

        Assert.AreEqual(outputList, "487572726168");

    }

Any pointers will be much appreciated. 任何指针将不胜感激。

Update 更新资料

I think you are thinking that a number can either be in decimal or binary or hexadecimal, etc. But that's not how it works. 我认为您认为数字可以是十进制,二进制或十六进制等。但这不是它的工作原理。 Numbers are numeric values that specify magnitude--decimal vs. hexadecimal is just how those values are represented. 数字是指定幅度的数值-十进制与十六进制就是表示这些值的方式。 So the numbers in listOfUshorts have a numeric value that can be expressed in either hexadecimal or any other base, such as decimal (the underlying base is actually binary, neither hex or decimal). 因此, listOfUshorts中的数字具有可以用十六进制或任何其他基数表示的数值,例如十进制(基础基数实际上是二进制,既不是十六进制也不是十进制)。

I've updated the code below to prove this: I have inserted new Debug.Asserts below, where I assert that each item is the expected hexadecimal value. 我更新了下面的代码以证明这一点:在下面插入了新的Debug.Asserts ,在这里我断言每个项目都是期望的十六进制值。 I also assert their equivalent decimal value, and then I assert that the hexadecimal and decimal values are directly equivalent to each other. 我还断言了它们的等效十进制值,然后断言了十六进制和十进制值彼此直接等效。


Original 原版的

Seems to me like you basically had it. 在我看来,就像您基本上拥有它一样。 However, the only time you need to convert to hex is for human-readable-comparison purposes. 但是,唯一需要转换为十六进制的操作是出于人类可读比较的目的。 So you don't need two lists ( output and outputList ). 因此,您不需要两个列表( outputoutputList )。 Internally you can always deal with the numeric values as they are, without conversion, as long as you always deal with them in the same base (whether decimal or hexadecimal or anything else). 在内部,只要始终以相同的底数(无论是十进制,十六进制还是其他形式)处理数字值,就可以直接处理它们而无需转换。

Here's basically the same thing, with a few tweaks. 这基本上是相同的东西,但有一些调整。 I don't have it as a test fixture, so I don't have Assert.AreEqual --I used Debug.Assert instead. 我没有将其作为测试装置,所以没有Assert.AreEqual我改用Debug.Assert。 I also put the hex formatting for display/comparison into its own function, since it's only needed for test purposes. 我还将显示/比较的十六进制格式放入其自己的函数中,因为仅出于测试目的才需要它。

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ushort[] result = AsciiToHexConversionTest();

            String outputAsHexString = DecodeToHexString(result);

            Debug.Assert(outputAsHexString == "0x4875,0x7272,0x6168");

            Console.WriteLine(outputAsHexString);
            var readKey = Console.ReadKey();
        }

        public static ushort[] AsciiToHexConversionTest()
        {
            var inputStr = "Hurrah";

            char[] values = inputStr.ToCharArray();
            List<ushort> listOfUshorts = new List<ushort>();

            ushort mask = (ushort)0x00FF;
            for (int i = 0; i < values.Length; i += 2)
            {
                //This approach assumes stuffing the lower 8 bits of two chars into the upper and lower half of a ushort
                ushort first = values[i];
                ushort second = (ushort)(mask & values[i + 1]); //mask is for safety.  Must ensure that top byte is 0 so that | below goes ok.
                listOfUshorts.Add((ushort)((first << 8) | second));
            }

            //demonstrate hexadecimal values
            Debug.Assert(listOfUshorts[0] == 0x4875);
            Debug.Assert(listOfUshorts[1] == 0x7272);
            Debug.Assert(listOfUshorts[2] == 0x6168);

            //demonstrate decimal values
            Debug.Assert(listOfUshorts[0] == 18549);
            Debug.Assert(listOfUshorts[1] == 29298);
            Debug.Assert(listOfUshorts[2] == 24936);

            //directly demonstrate equality of decimal and hexadecimal representations
            Debug.Assert(0x4875 == 18549);
            Debug.Assert(0x7272 == 29298);
            Debug.Assert(0x6168 == 24936);

            return listOfUshorts.ToArray();
        }

        public static string DecodeToHexString(ushort[] list)
        {
            StringBuilder finalOutput = new StringBuilder();
            foreach (var item in list)
            {
                finalOutput.Append(String.Format("0x{0:X},", item));
            }
            finalOutput.Remove(finalOutput.Length - 1, 1); //Remove final comma
            return finalOutput.ToString();
        }
    }
}

@Purusartha, there is an error in the ushort[] you give, the final hex value should be 0x6168 not 0x6148. @Purusartha,您输入的ushort []存在错误,最终的十六进制值应为0x6168,而不是0x6148。 I did it like this: 我这样做是这样的:

string inputStr = "Hurrah";
char[] values = inputStr.ToCharArray();
ushort[] packed = new ushort[values.Length / 2];
for (int i = 0; i < values.Length - 1; i+=2)
{
    packed[i / 2] = (ushort)(values[i] * 0x100 + values[i + 1]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM