Convert hexadecimal characters into byte Arrays

Source: Internet
Author: User

In computer systems, the commonly used encoding generally uses a hexadecimal string instead of a binary string. Two hexadecimal numbers can represent exactly one byte, the hexadecimal format is shorter. during conversion, a hexadecimal number can have four digits at most. But when we writeProgramGenerally, byte arrays are used. How is the conversion between them? The following describes how they are converted to each other.

Hexadecimal string to byte array

 
Public Static Byte[] Hexstringtobyte (StringHexstring)

{

 
Char[] Charlist = hexstring. tochararray ();

Byte[] Resultlist =New Byte[Charlist. Length/2];

 

 
IntBytecount = 0;

 

 
For(IntI = 0; I <charlist. length; I + = 2)

 
{

 
// A byte is equivalent to two hexadecimal numbers.

ByteB = 0x00;

 
B | = convert. tobyte ("0x0"+ Charlist [I], 16 );

 
B <= 4;// Shift operation, four digits left

B | = convert. tobyte ("0x0"+ Charlist [I + 1], 16 );

 
Resultlist [bytecount] = B;

 
Bytecount ++;

 
}

 

 
ReturnResultlist;

}

Byte array to hexadecimal string

Public StringBytetostring (Byte[] Bytelist)

{

 
Stringbuilder sbresult =NewStringbuilder ();

Foreach(ByteOnebyteInBytelist)

{

 
StringTempstr = string. Format ("{0: X2 }", Onebyte );

 
Sbresult. append (tempstr );

 
}

ReturnSbresult. tostring ();

 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.