Link to home
Start Free TrialLog in
Avatar of Winston Smith
Winston SmithFlag for Canada

asked on

How to convert 16 bit byte to 2 string characters

I have a C# app that reads binary data from an app through a C++ import.

The data i am trying to read is held in short integers so i need to split the int16 into its byte pairs and read the values into its two strings.

I do it in VB.net with the following function
 Public Shared Function ByteToString(ByVal bytStr As Byte) As String
        Dim strCon As String        'hold the string
        strCon = Convert.ToChar(bytStr)
        'return the string
        Return strCon
    End Function

But i cannot find the same functionality in C#.

Supposedly this should work but all i store then is the numeric value of the byte
bytByteArr[1].ToString();

Thanks for any help!!
Avatar of Winston Smith
Winston Smith
Flag of Canada image

ASKER

Little more info

I read in from a byte array 2 bytes at a time
'read the next 2 bytes in                  
                bytByteArr = brContents.ReadBytes(2);

for example first two bytes are 73 and 114 - which are the letters I and r
Then i get 101 and 110 - which are e and n respectively

Hope this helps my clear as mud question
If you have a 16-bit integer:

int input = 1234;
int lower = input & 0x00FF;
int upper = (input & 0xFF00) >> 4;
Sorry, that should be a shift of 8-bits not 4!

If you have a 16-bit integer:

int input = 1234;
int lower = input & 0x00FF;
int upper = (input & 0xFF00) >> 8;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of numberkruncher
numberkruncher
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
numberkruncher, that works great. i think i am taking the long way at getting what i need done but your idea gets my string out of the binary data.

A question though. I know the field i am grabbing can be up to 20 ints long, thats 40 short ints that i grab. At any point there can be null terminators within the data ('\0' i belive is the code from C++ i am grabbing). How can i strip this from my string or toss it as i create it?

Thanks!!
Its OK, i found it.

//set the char we want to trim, in this case the nulls
        char[] trimNulls = { '\0' };

        //return the result
        return strTextResult.Trim(trimNulls);

Thanks!!