your programing

C #에서 문자열을 바이트 배열로 변환

lovepro 2020. 10. 3. 11:25
반응형

C #에서 문자열을 바이트 배열로 변환


VB에서 C #으로 변환하고 있습니다. 이 문의 구문에 문제가 있습니다.

if ((searchResult.Properties["user"].Count > 0))
{
    profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}

그런 다음 다음 오류가 표시됩니다.

인수 1 : 'object'에서 'byte []'로 변환 할 수 없습니다.

'System.Text.Encoding.GetString (byte [])'에 대한 최상의 오버로드 된 메서드 일치에 잘못된 인수가 있습니다.

게시물을 기반으로 코드를 수정하려고 했지만 여전히 성공하지 못했습니다.

string User = Encoding.UTF8.GetString("user", 0);

어떤 제안?


이미 바이트 배열이있는 경우 해당 바이트 배열로 만드는 데 사용 된 인코딩 유형을 알아야합니다.

예를 들어, 바이트 배열이 다음과 같이 생성 된 경우 :

byte[] bytes = Encoding.ASCII.GetBytes(someString);

다음과 같은 문자열로 다시 변환해야합니다.

string someString = Encoding.ASCII.GetString(bytes);

상속 한 코드에서 바이트 배열을 만드는 데 사용 된 인코딩을 찾을 수 있으면 설정해야합니다.


먼저 System.Text네임 스페이스를 추가합니다.

using System.Text;

그런 다음이 코드를 사용하십시오.

string input = "some text"; 
byte[] array = Encoding.ASCII.GetBytes(input);

그것을 고칠 수 있기를 바랍니다!


또한 확장 메서드사용하여 string아래와 같이 형식에 메서드 를 추가 할 수 있습니다 .

static class Helper
{
   public static byte[] ToByteArray(this string str)
   {
      return System.Text.Encoding.ASCII.GetBytes(str);
   }
}

그리고 아래와 같이 사용하십시오.

string foo = "bla bla";
byte[] result = foo.ToByteArray();

static byte[] GetBytes(string str)
{
     byte[] bytes = new byte[str.Length * sizeof(char)];
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     return bytes;
}

static string GetString(byte[] bytes)
{
     char[] chars = new char[bytes.Length / sizeof(char)];
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     return new string(chars);
}

var result = System.Text.Encoding.Unicode.GetBytes(text);

이것을 사용하십시오

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

다음 접근 방식은 문자가 1 바이트 인 경우에만 작동합니다. (기본 유니 코드는 2 바이트이므로 작동하지 않습니다.)

public static byte[] ToByteArray(string value)
{            
    char[] charArr = value.ToCharArray();
    byte[] bytes = new byte[charArr.Length];
    for (int i = 0; i < charArr.Length; i++)
    {
        byte current = Convert.ToByte(charArr[i]);
        bytes[i] = current;
    }

    return bytes;
}

간단하게


Ali의 답변을 바탕 으로 사용하려는 인코딩을 선택적으로 전달할 수있는 확장 방법을 권장합니다.

using System.Text;
public static class StringExtensions
{
    /// <summary>
    /// Creates a byte array from the string, using the 
    /// System.Text.Encoding.Default encoding unless another is specified.
    /// </summary>
    public static byte[] ToByteArray(this string str, Encoding encoding = Encoding.Default)
    {
        return encoding.GetBytes(str);
    }
}

그리고 아래와 같이 사용하십시오.

string foo = "bla bla";

// default encoding
byte[] default = foo.ToByteArray();

// custom encoding
byte[] unicode = foo.ToByteArray(Encoding.Unicode);

JustinStolle의 편집 수정 (Eran Yogev의 BlockCopy 사용).

제안 된 솔루션은 실제로 인코딩을 사용하는 것보다 빠릅니다. 문제는 길이가 고르지 않은 바이트 배열을 인코딩하는 데 작동하지 않는다는 것입니다. 주어진대로 경계를 벗어난 예외가 발생합니다. 길이를 1 씩 늘리면 문자열에서 디코딩 할 때 후행 바이트가 남습니다.

For me, the need came when I wanted to encode from DataTable to JSON. I was looking for a way to encode binary fields into strings and decode from string back to byte[].

I therefore created two classes - one that wraps the above solution (when encoding from strings it's fine, because the lengths are always even), and another that handles byte[] encoding.

I solved the uneven length problem by adding a single character that tells me if the original length of the binary array was odd ('1') or even ('0')

As follows:

public static class StringEncoder
{
    static byte[] EncodeToBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    static string DecodeToString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }
}

public static class BytesEncoder
{
    public static string EncodeToString(byte[] bytes)
    {
        bool even = (bytes.Length % 2 == 0);
        char[] chars = new char[1 + bytes.Length / sizeof(char) + (even ? 0 : 1)];
        chars[0] = (even ? '0' : '1');
        System.Buffer.BlockCopy(bytes, 0, chars, 2, bytes.Length);

        return new string(chars);
    }
    public static byte[] DecodeToBytes(string str)
    {
        bool even = str[0] == '0';
        byte[] bytes = new byte[(str.Length - 1) * sizeof(char) + (even ? 0 : -1)];
        char[] chars = str.ToCharArray();
        System.Buffer.BlockCopy(chars, 2, bytes, 0, bytes.Length);

        return bytes;
    }
}

Does anyone see any reason why not to do this?

mystring.Select(Convert.ToByte).ToArray()

This question has been answered sufficiently many times, but with C# 7.2 and the introduction of the Span type, there is a faster way to do this in unsafe code:

public static class StringSupport
{
    private static readonly int _charSize = sizeof(char);

    public static unsafe byte[] GetBytes(string str)
    {
        if (str == null) throw new ArgumentNullException(nameof(str));
        if (str.Length == 0) return new byte[0];

        fixed (char* p = str)
        {
            return new Span<byte>(p, str.Length * _charSize).ToArray();
        }
    }

    public static unsafe string GetString(byte[] bytes)
    {
        if (bytes == null) throw new ArgumentNullException(nameof(bytes));
        if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
        if (bytes.Length == 0) return string.Empty;

        fixed (byte* p = bytes)
        {
            return new string(new Span<char>(p, bytes.Length / _charSize));
        }
    }
}

Keep in mind that the bytes represent a UTF-16 encoded string (called "Unicode" in C# land).

Some quick benchmarking shows that the above methods are roughly 5x faster than their Encoding.Unicode.GetBytes(...)/GetString(...) implementations for medium sized strings (30-50 chars), and even faster for larger strings. These methods also seem to be faster than using pointers with Marshal.Copy(..) or Buffer.MemoryCopy(...).


If the result of, 'searchResult.Properties [ "user" ] [ 0 ]', is a string:

if ( ( searchResult.Properties [ "user" ].Count > 0 ) ) {

   profile.User = System.Text.Encoding.UTF8.GetString ( searchResult.Properties [ "user" ] [ 0 ].ToCharArray ().Select ( character => ( byte ) character ).ToArray () );

}

The key point being that converting a string to a byte [] can be done using LINQ:

.ToCharArray ().Select ( character => ( byte ) character ).ToArray () )

And the inverse:

.Select ( character => ( char ) character ).ToArray () )

This work for me, after that I could convert put my picture in a bytea field in my database.

using (MemoryStream s = new MemoryStream(DirEntry.Properties["thumbnailphoto"].Value as byte[]))
{
    return s.ToArray();
}

참고URL : https://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp

반응형