Data Transformation in C#

        private void testConvert()
        {
            string a = "1110101010010010111110";
            label1.Text = bin2hex(a).ToString();//Binary to hexadecimal 3AA4BE

            string b = "7D3C";
            label2.Text = hex2bin(b).ToString();//Hexadecimal to binary 0111110100111100

            int c =198;
            label3.Text = c.ToString("X4");//Decimal to hexadecimal, and padded with 0 to 4 digits 00C6

            string d = "AB0C";
            label4.Text = Convert.ToInt32(d, 16).ToString();//hexadecimal to decimal (int32) 43788
            //Convert.ToByte(d,16)//Convert from hexadecimal to decimal (byte), pay attention to the size
        }
        private StringBuilder hex2bin(string sHex)
        {
            StringBuilder sbBin = new StringBuilder();
            foreach (char c in sHex)
            {
                int a = Convert.ToInt32(c.ToString(), 16);//hexadecimal to decimal
                sbBin.Append(Convert.ToString(a, 2).PadLeft(4,'0'));//Convert from decimal to binary and add 0 to 4 digits in front
            }
            return sbBin;
        }
        private StringBuilder bin2hex(string sBin)
        {
            int count=0;
            StringBuilder sbHex=new StringBuilder();
            count=sBin.Length / 4;
            //First judge the length, if it is less than a multiple of 4, add 0 in front
            if (sBin.Length % 4 != 0) sBin = sBin.PadLeft( ++count * 4, '0');
            for (int i = 0; i < count; i++)
            {
                int a = Convert.ToInt32(sBin.Substring(i*4,4),2);//Binary to decimal
                sbHex.Append(a.ToString("X"));//Decimal to hexadecimal
            }
            return sbHex;
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326270043&siteId=291194637