2016-12-19 37 views
1

我有兩個8位數字的十六進制字符串。我需要對這兩個十六進制字符串進行應用和操作,然後將右移到7位並獲取十進制值。我已經嘗試將Hex字符串轉換爲長度爲4的字節數組(8 * 2 = 32位= 4字節),並對相同順序的各個字節進行了操作,將結果保存到另一個長度爲4的字節數組中。如何進行位移到這個字節數組?右移字節數組

Ex : data1 in hex: 0x40003019, 
    data1 in bits: 0100-0000 0000-0000 0011-0000 0001-1001, 
    data1 in bytes: 64 0 48 25, 
    data2 in hex: 0x00FFFF80, 
    data2 in bits : 0000-0000 1111-1111 1111-1111 1000-0000, 
    data2 in bytes : 0 255 255 128 

AND data1Bytes之間操作,data2Bytes其給出輸出:bytearray1 [0,0,48,0](對於這些0000-0000 0000-0000 0011-0000 0000-0000和十進制值的位是12,288)。

直到這一步,我所有的轉換和計算都按預期工作。 現在我需要右移7位的這個結果應該給0000-0000 0000-0000 0000-0000 0110-0000(十進制值爲96)。

1)我試圖轉換字節數組int和應用右移

var res = BitConverter.ToInt32(bytearray1, 0); 
var shift = res >> 7; 

但解析度= 3145728(它應該是12228)和換檔= 24576(其應爲96)

2 )我已經累轉換bytearray1 [0,0,48,0]到BitArray但在所得BitArray比特以相反的順序

var bitArray = new BitArray(bytearray1); 

bitArray [0] ... bitArray [19] = FALSE,bitArray [20 ] = bitArray [21] = true,bitArray [22] ... bitArray [31] = false。

bitArray [0] ----------- [31]:0000 0000 0000 0000 0000 1100 0000 0000,

比特移位該結果錯誤的值。 請幫我這個,我失蹤了?

+1

你說「右移」,但你的例子左移00110000到01100000.哪一個是正確的?也許你只需要用'<<'替換'>>'...... –

+0

@MthetheWWatson嗨,如果你看到最後一位的表示形式,我剛剛在將bytearray1轉換爲bitArray之後顯示了位數組中存儲的位。在完成和操作字節之後,我需要對我的最終結果進行移位。 –

+1

嗯,但你說'現在我需要右移7位的這個結果,應該給0000-0000 0000-0000 0000-0000 ** 0110-0000 **',鑑於上一步有'0000-0000 0000-0000 ** 0011-0000 ** 0000-0000',是左移。 –

回答

0

我不知道這是爲什麼不爲你工作,但是當我嘗試了明顯的方法工作。

首先假設你有兩個十六進制數在uint值:

uint data1 = 0x40003019; 
uint data2 = 0x00FFFF80; 

現在只要和他們在一起,然後將結果右移:

uint anded = data1 & data2; 
uint result = anded >> 7; // Gives 96 as requested. 

這給出了96結果。

如果輸入的形式爲string str = "0x40003019";的字符串,你可以將其轉換爲uint像這樣:

uint data1 = uint.Parse(str.Substring(2), NumberStyles.HexNumber); 

str.SubString(2)就是脫光了"0x"前綴。如果輸入字符串沒有"0x"前綴,則這是不必要的。

+0

嗨,是的,我也以同樣的方式做了你喜歡的事情,並得到了結果。謝謝你的幫助。 –

-2

嘗試以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 


namespace ConsoleApplication33 
{ 

    class Program 
    { 

     static void Main(string[] args) 
     { 
      List<string> digits = new List<string>() { 
            "0000","0001","0010","0011","0100","0101","0110","0111", 
            "1000","1001","1010","1011","1100","1101","1110","1111" 
           }; 
      string input = "0100-0000 0000-0000 0011-0000 0001-1001"; 
      byte[] bytes = input.Split(new char[] { '-', ' ' }).Select(x => (byte)digits.IndexOf(x)).ToArray(); 
      ulong number = BitConverter.ToUInt64(bytes,0); 
      Console.WriteLine(number); 
      Console.ReadLine(); 
     } 
    } 


} 
+1

你會認爲有7k代表的人現在可以正確地格式化他們的代碼嗎? – Liam

+1

這也不符合OP的要求。你從來沒有執行過一點轉變? – Liam

+0

是的,與BitConverter。 – jdweng