Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 45267
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T15:46:56+00:00 2026-05-10T15:46:56+00:00

I need to convert a (possibly) null terminated array of ascii bytes to a

  • 0

I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I’ve found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte*) constructor which contains a warning in it’s remarks:

‘The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default).

Note: * Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. * …

* If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. * ‘

Now, I’m positive that the way the string is encoded will never change… but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn’t run screaming from using String.String(sbyte*) for this purpose?

using System; using System.Text;  namespace FastAsciiBytesToString {     static class StringEx     {         public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength)         {             int maxIndex = offset + maxLength;              for( int i = offset; i < maxIndex; i++ )             {                 /// Skip non-nulls.                 if( buffer[i] != 0 ) continue;                 /// First null we find, return the string.                 return Encoding.ASCII.GetString(buffer, offset, i - offset);             }             /// Terminating null not found. Convert the entire section from offset to maxLength.             return Encoding.ASCII.GetString(buffer, offset, maxLength);         }          public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset)         {             string result = null;              unsafe             {                 fixed( byte* pAscii = &buffer[offset] )                 {                      result = new String((sbyte*)pAscii);                 }             }              return result;         }     }      class Program     {         static void Main(string[] args)         {             byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 };              string result = asciiBytes.AsciiBytesToString(3, 6);              Console.WriteLine('AsciiBytesToString Result: \'{0}\'', result);              result = asciiBytes.UnsafeAsciiBytesToString(3);              Console.WriteLine('UnsafeAsciiBytesToString Result: \'{0}\'', result);              /// Non-null terminated test.             asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' };              result = asciiBytes.UnsafeAsciiBytesToString(3);              Console.WriteLine('UnsafeAsciiBytesToString Result: \'{0}\'', result);              Console.ReadLine();         }     } } 
  • 1 1 Answer
  • 3 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T15:46:56+00:00Added an answer on May 10, 2026 at 3:46 pm

    Any reason not to use the String(sbyte*, int, int) constructor? If you’ve worked out which portion of the buffer you need, the rest should be simple:

    public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length) {     unsafe     {        fixed (byte* pAscii = buffer)        {             return new String((sbyte*)pAscii, offset, length);        }     } } 

    If you need to look first:

    public static string UnsafeAsciiBytesToString(byte[] buffer, int offset) {     int end = offset;     while (end < buffer.Length && buffer[end] != 0)     {         end++;     }     unsafe     {        fixed (byte* pAscii = buffer)        {             return new String((sbyte*)pAscii, offset, end - offset);        }     } } 

    If this truly is an ASCII string (i.e. all bytes are less than 128) then the codepage problem shouldn’t be an issue unless you’ve got a particularly strange default codepage which isn’t based on ASCII.

    Out of interest, have you actually profiled your application to make sure that this is really the bottleneck? Do you definitely need the absolute fastest conversion, instead of one which is more readable (e.g. using Encoding.GetString for the appropriate encoding)?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to convert from a SQLVARCHAR to a string data type Variable definitions
Using link what is the easiest way to convert a list of longs to
I have the below code and I'd need to convert a string to a
What is the safe/portable way to convert a number to a string (and the
Possible Duplicate: How can I convert ereg expressions to preg in PHP? I need
Possible Duplicate: How do I convert byte[] to stream in C#? I need to
I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM
I need to convert a named instance of SQL server 2005, to a default
I need to convert HTML documents into valid XML, preferably XHTML. What's the best
I need to convert a value which is in a DateTime variable into a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.