0

I use a NFC-Reader to read data. The data will be stores as byte[] bytes_credentials. Receiving data is working fine but now I want to encode the 16 byte Array to String. I use string str = Encoding.Default.GetString(new_data); for decoding the array. The string output is working fine if the byte Array is fully "booked up" (16 of 16 bytes used), for example: This is an test! -> 54 68 69 73 20 69 73 20 61 6e 20 74 65 73 74 21. The problem i am facing is, that if the NFC-Array is not fully "booked up", the Array look like this: This is! -> 54 68 69 73 20 69 73 21 00 00 00 00 00 00 00 00. The output in console looks like this: This is!????????.

How can I CHECK and REMOVE the empty bytes (00) from the Array. So that the Output looks like this: This is!.

Thank you for helping!!! I have checked previous posts but no of them are working for me...

2
  • 3
    If you're programming in C#, why did you add the totally irrelevant C language tag? Despite the names being similar, they are two very different languages. Commented Oct 2, 2022 at 13:07
  • 1
    As it stands you could just do yourBytes.Where(b => b != 0) or possibly yourBytes.Reverse().SkipWhile(b => b == 0).Reverse() But it sounds like you are reading into a buffer, but not using the resulting number of bytes read to pass into Encoding.GetString. Please show your code so we can understand how to improve it. Commented Oct 2, 2022 at 14:03

1 Answer 1

1

You can use LINQ to filter your array further:

using System.Text;

var bytes_credentials = new byte[]
{
    0x54,
    0x68,
    0x69,
    0x73,
    0x20,
    0x69,
    0x73,
    0x21,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0
};

Console.WriteLine(Encoding.Default.GetString(
    bytes_credentials.Where(b => b != 0).ToArray()
));

To learn more about LINQ, take a look here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.