Как преобразовать шестнадцатеричное число в массив байтов?

После некоторого расследования я смог воссоздать вашу проблему, и, похоже, она связана с тем, как Жасмин обрабатывает все ловушки. Существует полное обсуждение здесь и здесь , но в основном (и удивительно) кажется, что все в вашем тестовом файле, не объявленном в описании, будет выполнено до ЛЮБОГО [119 ] выполняются тесты, включая beforeAll hooks . Это удивляет меня, так как я почти уверен, что раньше использовал все снаружи, раньше описывал без проблем, но сейчас не могу это проверить.

Однако, если вы объявите свой хук beforeAll в своем описании, он будет поднят и все еще будет выполняться перед вашими тестами точно так же, как вы ожидаете, что он будет вести себя сейчас.

Можете ли вы попробовать переместить ваши блоки beforeAll в пределах вашего описания, как показано ниже:

Spec1.js

describe('Create Accounts', function () {
   beforeAll(function () { 
       originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
       jasmine.DEFAULT_TIMEOUT_INTERVAL = globalconstants.wait10Mints;
       browser.waitForAngularEnabled(false);
       browser.get(env.appUrl);
       browser.getTitle().then(function (title) {
           expect(title, "Browser title is not the expected. But " + browser.getTitle()).toBe("Valueone");
       });
       browser.waitForAngularEnabled(true);
       loginPage.login();

       commonPage.navigateToAccounts();
       accountsPage.deleteAccounts(number); 
   });

   it("Create Savings", function () {
       something 
   });

   it("Create current account", function () {
      something 
   });

});

Spec2.js [ 1112]

describe('Create Users', function () {
    beforeAll(function () {
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = globalconstants.wait10Mints;
        browser.waitForAngularEnabled(false);
        browser.get(env.appUrl);
        browser.getTitle().then(function (title) {
            expect(title, "Browser title is not the expected. But " + browser.getTitle()).toBe("Valueone");
        });
        browser.waitForAngularEnabled(true);
        loginPage.login();

        commonPage.navigateToUsers();
        usersPage.deleteUsers(name);
    });

    it("Create user", function () {
        something
    });

    it("Create user", function () {
        something
    });
})

10
задан user82334 12 May 2009 в 17:56
поделиться

5 ответов

Примерно так:

using System;

public static class Parser
{    
    static void Main()
    {
        string hex = "0xBAC893CAB8B7FE03C927417A2A3F6A6"
                     + "0BD30FF35E250011CB25507EBFCD5223B";
        byte[] parsed = ParseHex(hex);
        // Just for confirmation...
        Console.WriteLine(BitConverter.ToString(parsed));
    }

    public static byte[] ParseHex(string hex)
    {
        int offset = hex.StartsWith("0x") ? 2 : 0;
        if ((hex.Length % 2) != 0)
        {
            throw new ArgumentException("Invalid length: " + hex.Length);
        }
        byte[] ret = new byte[(hex.Length-offset)/2];

        for (int i=0; i < ret.Length; i++)
        {
            ret[i] = (byte) ((ParseNybble(hex[offset]) << 4) 
                             | ParseNybble(hex[offset+1]));
            offset += 2;
        }
        return ret;
    }        

    static int ParseNybble(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c-'0';
        }
        if (c >= 'A' && c <= 'F')
        {
            return c-'A'+10;
        }
        if (c >= 'a' && c <= 'f')
        {
            return c-'a'+10;
        }
        throw new ArgumentException("Invalid hex digit: " + c);
    }
}

(РЕДАКТИРОВАТЬ: Теперь немного эффективнее - подстроки не требуются ...)

Возможно, ParseNybble мог бы быть более эффективным. Например, переключатель / case может быть более эффективным:

    static int ParseNybble(char c)
    {
        switch (c)
        {
            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                return c-'0';
            case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
                return c-'A'+10;
            case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
                return c-'a'+10;
        }
        throw new ArgumentException("Invalid hex digit: " + c);
    }

или, возможно, поисковый массив:

    // Omitted for brevity... I'm sure you get the gist
    private static readonly int[] NybbleLookup = BuildLookup();

    private int ParseNybble(char c)
    {
        if (c > 'f')
        {
            throw new ArgumentException("Invalid hex digit: " + c);
        }
        int ret = NybbleLookup[c];
        if (ret == -1)
        {
            throw new ArgumentException("Invalid hex digit: " + c);
        }
        return ret;
    }

Я не тестировал ни один из них и не знаю, какой из них будет самым быстрым. , Однако текущее решение, вероятно, является самым простым.

21
ответ дан 3 December 2019 в 14:06
поделиться

Рассмотрите возможность использования класса Framework, который уже предоставляет возможность выполнять шестнадцатеричное преобразование, XmlReader, например:

public static byte[] HexToBytes(this string hexEncodedBytes, int start, int end)
{
    int length = end - start;
    const string tagName = "hex";
    string fakeXmlDocument = String.Format("<{1}>{0}</{1}>",
                           hexEncodedBytes.Substring(start, length),
                           tagName);
    var stream = new MemoryStream(Encoding.ASCII.GetBytes(fakeXmlDocument));
    XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings());
    int hexLength = length / 2;
    byte[] result = new byte[hexLength];
    reader.ReadStartElement(tagName);
    reader.ReadContentAsBinHex(result, 0, hexLength);
    return result;
}

использование:

string input = "0xBAC893CAB8B7FE03C927417A2A3F6A60BD30FF35E250011CB255";
byte[] bytes = input.HexToBytes(2, input.Length);
7
ответ дан 3 December 2019 в 14:06
поделиться

Просто:

string hexnum = "0000000F"; // Represents 15
int value = int.Parse(hexnum, System.Globalization.NumberStyles.HexNumber);

Все, что вам нужно сделать, это чтобы int разделил шестнадцатеричное число на группы по 8 шестнадцатеричных цифр (шестнадцатеричные числа составляют 4 бита каждая, а тип int CLR - 32 бита, следовательно, 8 цифр на целое). Также существует функция byte.Parse (), которая работает так же, но передает две шестнадцатеричные цифры одновременно.

3
ответ дан 3 December 2019 в 14:06
поделиться

Примерно так:

    public byte[] ParseHexString(string text)
    {
        if ((text.Length % 2) != 0)
        {
            throw new ArgumentException("Invalid length: " + text.Length);
        }

        if (text.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
        {
            text = text.Substring(2);
        }

        int arrayLength = text.Length / 2;
        byte[] byteArray = new byte[arrayLength];
        for (int i = 0; i < arrayLength; i++)
        {
            byteArray[i] = byte.Parse(text.Substring(i*2, 2), NumberStyles.HexNumber);
        }

        return byteArray;
    }
3
ответ дан 3 December 2019 в 14:06
поделиться

Вам нужно будет немного изменить это (например, пропустить первые два символа), но он обрабатывает пробелы в строке:

    /// <summary>
    /// Decodes a hex string, ignoring all non-hex characters, and stores
    /// the decodes series of bytes into the shared buffer. This returns
    /// the number of bytes that were decoded.
    /// <para>Hex characters are [0-9, a-f, A-F].</para>
    /// </summary>
    /// <param name="hexString">String to parse into bytes.</param>
    /// <param name="buffer">Buffer into which to store the decoded binary data.</param>
    /// <returns>The number of bytes decoded.</returns>
    private static int DecodeHexIntoBuffer(string hexString, byte[] buffer)
    {
        int count = 0;

        bool haveFirst = false;
        bool haveSecond = false;
        char first = '0';
        char second = '0';

        for (int i = 0; i < hexString.Length; i++)
        {
            if (!haveFirst)
            {
                first = hexString[i];
                haveFirst = char.IsLetterOrDigit(first);

                // we have to continue to the next iteration
                // or we will miss characters
                continue;
            }

            if (!haveSecond)
            {
                second = hexString[i];
                haveSecond = char.IsLetterOrDigit(second);
            }

            if (haveFirst && haveSecond)
            {
                string hex = "" + first + second;

                byte nextByte;
                if (byte.TryParse(hex, NumberStyles.HexNumber, null, out nextByte))
                {
                    // store the decoded byte into the next slot of the buffer
                    buffer[count++] = nextByte;
                }

                // reset the flags
                haveFirst = haveSecond = false;
            }
        }

        return count;
    }
1
ответ дан 3 December 2019 в 14:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: