How to send Data command to IT_100 Serial Port? - c#

I have a DSC IT_100 . I want to send data command to invoke alarm. However i couldnt handle it.
SerialPort myPort = new SerialPort("COM6");
myPort.BaudRate = 9600;
myPort.Parity = Parity.None;
myPort.StopBits = StopBits.One;
myPort.DataBits = 8;
myPort.Handshake = Handshake.None;
myPort.Open();
I am sending data as HEX. Here is my program
var sendData = GetBytes("6541D2CRLF");
myPort.WriteLine(sendData);
private static string GetBytes(string input)
{
string result = "";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
int value = Convert.ToInt32(letter);
result += String.Format("{0:X}", value);
}
return result;
}
In programming sheet it says that :
Could you please help me how to send this data to COM..

I believe you need to follow method:
public static byte[] BuildPacket(string Command, string DataBytes)
{
List<byte> output = new List<byte>();
// Add command text
output.AddRange(Encoding.ASCII.GetBytes(Command));
// Add data bytes
output.AddRange(Encoding.ASCII.GetBytes(DataBytes));
// Add checksum
byte chkSum = 0;
foreach(byte b in output )
{
chkSum += b;
}
output.AddRange(Encoding.ASCII.GetBytes(chkSum.ToString("X")));
output.AddRange(Encoding.ASCII.GetBytes(Environment.NewLine));
return output.ToArray();
}
To get the bytes you need to send to the port use the method like this:
var sendData = BuildPacket("654","3");
myPort.WriteLine(sendData);
Having looked at your programming sheet there seems to an error:
The data bytes shown is incorrect character 1 is NOT 33 in hex, it is 31. I believe that the data bytes should be 3 in you case. You can play around with this but when I use the value 3 for the data bytes I get the check sum they have calculated when I use 1 I do not.
Please note I don't have a COM port or your device to test this so your results may vary.
I read the manual for the device here.

I have this working. After a night of headscratching.
The key is the checksum calculation. The code below connects to my IT-100 (running on a IP/Serial adapter), and sends it both a "Poll" command and a "Status" command.
The hard part (that took me several hours of trial and error) was the bizzare checksum calculation. The algorithm, from the manual, is really strange:
Add all the ASCII Codes together
Truncate to 8 bits
Create a high and low nibble
Convert the values of the nibbles (0x01 -> 0x0F) to the ASCII code for the character.
For example, in step 4 above: 0x01 = '1' = 0x31 = Beyond Stupid
My complete code is below.
using System;
using System.Net.Sockets;
using System.Text;
namespace IT100TestDriver
{
class Program
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var address = System.Net.IPAddress.Parse("192.168.1.250");
System.Net.EndPoint ep = new System.Net.IPEndPoint(address, 1024);
s.Connect(ep);
byte[] buffer = new byte[1024];
NetworkStream ns = new NetworkStream(s);
AsyncCallback callback = null;
callback = ar =>
{
int bytesRead = ns.EndRead(ar);
string fromIT100 = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.Write(fromIT100);
ns.BeginRead(buffer, 0, 1024, callback, null);
};
Console.WriteLine("Connected to: {0}", ep.ToString());
ns.BeginRead(buffer, 0, 1024, callback, null);
while (true)
{
var ki = Console.ReadKey(true);
byte[] command = null;
switch (ki.KeyChar)
{
case 'p':
{
Console.WriteLine("Sending Ping");
command = Encoding.ASCII.GetBytes("000"); // ping
}
break;
case 's':
{
Console.WriteLine("Sending Status Request");
command = Encoding.ASCII.GetBytes("001"); // status request
}
break;
}
if (command != null)
{
byte[] crlf = { 0x0D, 0x0A };
ns.Write(command, 0, command.Length);
byte[] checksum = calculateChecksum(command);
ns.Write(checksum, 0, checksum.Length);
ns.Write(crlf, 0, crlf.Length);
}
}
}
private static byte[] calculateChecksum(byte[] dataToSend)
{
int sum = 0;
foreach(byte b in dataToSend)
{
sum += b;
}
int truncatedto8Bits = sum & 0x000000FF;
byte upperNibble = (byte)(((byte)(truncatedto8Bits & 0x000000F0)) >> 4);
byte lowerNibble = (byte) (truncatedto8Bits & 0x0000000F);
// value is 0x09, need to treat it as '9' and convert to ASCII (0x39)
byte upperNibbleAsAscii = (byte)nibbleToAscii(upperNibble);
byte lowerNibbleAsAscii = (byte)nibbleToAscii(lowerNibble);
return new byte[] { upperNibbleAsAscii, lowerNibbleAsAscii };
}
private static char nibbleToAscii(byte b)
{
switch (b)
{
case 0x00: return '0';
case 0x01: return '1';
case 0x02: return '2';
case 0x03: return '3';
case 0x04: return '4';
case 0x05: return '5';
case 0x06: return '6';
case 0x07: return '7';
case 0x08: return '8';
case 0x09: return '9';
case 0x0A: return 'A';
case 0x0B: return 'B';
case 0x0C: return 'C';
case 0x0D: return 'D';
case 0x0E: return 'E';
case 0x0F: return 'F';
default:
throw new ArgumentOutOfRangeException("Unknown Nibble");
}
}
}
}

Related

Sending multiple files from C# to C

I have a wpf gui that I want to upload files from and send to a C client .
I want to send 3 files and for some reason 1 of them is being sent and written (but it adds 8 nulls in the end and removes 4 of the first letters in the file)
and in the other two when I try to receive the size it says their size is 0
I've been stuck on this problem for a while now and i'm becoming depserate as i'm probably missing a small thing , if any of u could give a hand that'll mean a lot ! I really wanna know whats the problem in my code.
I have the files paths in an array and sending it in main like so
C# Main
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);//switch the port
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(ipPoint);
listenSocket.Listen(1);
Socket clientSocket = listenSocket.Accept();
for (int i = 0; i < 1; i++)
{
SendFile(clientSocket, filePaths[i]);
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
SendFile(C# side)
public static void SendFile(Socket clientSocket, string filePath)
{
if (File.Exists(filePath))
{
FileInfo fi = new FileInfo(filePath);
long file_size = fi.Length;
byte[] preBuffer;
using (var memoryStream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(memoryStream))
{
writer.Write(file_size);
}
preBuffer = memoryStream.ToArray();
byte[] fixedBuffer = new byte[4];
Array.Copy(preBuffer, 0, fixedBuffer, 0, 4);
Console.WriteLine(BitConverter.ToString(preBuffer));
Console.WriteLine(BitConverter.ToString(fixedBuffer)); //fixing the problem i had with the converting to array that it added 4 useless zeros.
clientSocket.Send(fixedBuffer); // sending size
}
byte[] data = new Byte[4096];
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
int actualRead;
do
{
actualRead = fs.Read(data, 0, data.Length);
clientSocket.Send(data);
file_size -= actualRead;
} while (file_size - filePath.Length > 0);
}
}
else
{
MessageBox.Show("File for the program is missing! lua/pcap/csv");
}
}
C Receive(built from 3 functions)
/*
============================================
General : function is responsible for receiving a length of data from the client
Parameters : sock - client socket to receive the data from
*buf - holds a pointer to the buffer that needs to update
bufsize - the length of the buffer
Return Value : returns TRUE when the data is read correctly
else, FALSE when there was a socket error or no bytes are received.
============================================
*/
bool recv_raw(SOCKET sock, void* buf, int bufsize)
{
unsigned char* pbuf = (unsigned char*)buf;
while (bufsize > 0) {
int num = recv(sock, pbuf, bufsize, 0);
if (num <= 0) { return false; }
pbuf += num;
bufsize -= num;
}
return true;
}
/*
===================================================
General : receives the length of the file and updates it
Parameters : sock - client socket to receive the data from
*filesize - holds a pointer to the size of the buffer that needs to update
filesize_len - the length of the file size pointer
Return Value : returns TRUE when the size is read correctly
else, FALSE when there was a socket error or no bytes are received.
===================================================
*/
bool recv_file_len(SOCKET sock, long* filesize)
{
if (!recv_raw(sock, filesize, sizeof(*filesize))) { return false; }
return true;
}
/*
================================================== =
General : writes to the lua file the data from the file
that was received in the socket
Parameters : sock - the socket between the client and server
*f - the file to write the data received to
Return Value : returns TRUE when everything was written to the file.
returns FALSE if there's no data received or detected a socket problem.
================================================== =
*/
bool write_data(SOCKET sock, FILE *f)
{
long filesize;//size of address
char buffer[BUFFER_SIZE];
if (!recv_file_len(sock, &filesize)) { return false; }
printf("file size (From C#) : %ld\n", filesize);
int n = recv_raw(sock, buffer, 8); // need to get the size of the name
if (filesize > 0)
{
do {
int num = min(filesize, BUFFER_SIZE);
if (!recv_raw(sock, buffer, num)) {
return false;
}
int offset = 0;
do
{
size_t written = fwrite(&buffer[offset], 1, num - offset, f);
if (written < 1) { return false; }
offset += written;
} while (offset < num);
filesize -= num;
} while (filesize > 0);
}
return true;
}
C Main
FILE* luafhandler = fopen("test.lua", "wb");//the new lua file
if (luafhandler == NULL)
{
fclose(luafhandler);
printf("GUI CONNECT lua file failed to open!\n");
}
FILE* pcapfhandler = fopen("test.pcap", "wb");//the new lua file
if (pcapfhandler == NULL)
{
fclose(pcapfhandler);
printf("GUI CONNECT pcap file failed to open!\n");
}
FILE* csvfhandler = fopen("AlgoTest.csv", "wb");//the new lua file
if (csvfhandler == NULL)
{
fclose(csvfhandler);
printf("GUI CONNECT csv file failed to open!\n");
}
else {
SOCKET sock1 = open_socket(5555, SERVER_IP);
bool check = write_data(sock1, luafhandler);
bool check1 = write_data(sock1, pcapfhandler);
bool check2 = write_data(sock1, csvfhandler);
fclose(luafhandler);
fclose(pcapfhandler);
fclose(csvfhandler);
}

How to convert Android AudioFormat.ENCODING_PCM_16BIT into uLaw or Linear in C#

I have developed two UDP multicast apps using .NET and Android. Both applications have Sender and Receiver. They are working well when I am using the same app on different devices/pc. But when I try to receive the stream from .NET App to Android or Android to .NET then getting noise voice. I have checked both apps' streaming metadata (byte) and their format is different. Android Audio Format is: AudioFormat.ENCODING_PCM_16BIT for Encoding and C# Receiver convert the coming bytes uLaw To Linear. I understand due to different algorithm implementation in both app, they are not taking the stream. Please check my code snippets for C# & Android.
C# Codes
public static Byte[] MuLawToLinear(Byte[] bytes, int bitsPerSample, int channels)
{
//Anzahl Spuren
int blockAlign = channels * bitsPerSample / 8;
//Für jeden Wert
Byte[] result = new Byte[bytes.Length * blockAlign];
for (int i = 0, counter = 0; i < bytes.Length; i++, counter += blockAlign)
{
//In Bytes umwandeln
int value = MulawToLinear(bytes[i]);
Byte[] values = BitConverter.GetBytes(value);
switch (bitsPerSample)
{
case 8:
switch (channels)
{
//8 Bit 1 Channel
case 1:
result[counter] = values[0];
break;
//8 Bit 2 Channel
case 2:
result[counter] = values[0];
result[counter + 1] = values[0];
break;
}
break;
case 16:
switch (channels)
{
//16 Bit 1 Channel
case 1:
result[counter] = values[0];
result[counter + 1] = values[1];
break;
//16 Bit 2 Channels
case 2:
result[counter] = values[0];
result[counter + 1] = values[1];
result[counter + 2] = values[0];
result[counter + 3] = values[1];
break;
}
break;
}
}
return result;
}
Android Codes
// Audio Configuration.
int sampleRate = 16000; // How much will be ideal?
int channelConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
boolean status = true;
String ip = getIntent().getStringExtra("ip");
final InetAddress destination = InetAddress
.getByName(ip);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleRate, channelConfig, audioFormat, minBufSize);
recorder.startRecording();
while (status) {
if (!startStreamThread) {
socket.disconnect();
socket.leaveGroup(destination);
break;
}
byte[] bytes = new byte[2 + buffer.length];
bytes[0] = 1;
bytes[1] = 2;
System.arraycopy(buffer, 0, bytes, 2, buffer.length);
String deviceIp = getIpAddress();
minBufSize = recorder.read(bytes, 0, bytes.length);
// putting buffer in the packet
packet = new DatagramPacket(bytes, bytes.length,
destination, DEFAULT_PORT);
Log.e("NewOutgoing", "" + packet.getData());
Log.e("NewDEstination; ", "" + destination);
// packet.setData(deviceIp.getBytes());
socket.send(packet);
}

Modbus function 0x06

Faced a problem. There is a 0x03 function, but I need to redo it in 0x06, I don’t understand how to do it.
I know that function 06 does not have a variable part. The value of one register is always transferred to it. But I can not understand what needs to be corrected. Please, help.
Here I create a package for functions:
private void BuildMessage(byte address, byte type, ushort start, ushort registers, ref byte[] message)
{
if (type == 3 || type == 16)
{
//Array to receive CRC bytes:
byte[] CRC = new byte[2];
message[0] = address;
message[1] = type;
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
message[4] = (byte)(registers >> 8);
message[5] = (byte)registers;
GetCRC(message, ref CRC);
message[message.Length - 2] = CRC[0];
message[message.Length - 1] = CRC[1];
}
else if (type == 6)
{
byte[] CRC = new byte[2];
message[0] = address;
message[1] = type;
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
message[4] = (byte)(registers >> 8);
message[5] = (byte)registers;
GetCRC(message, ref CRC);
message[6] = CRC[0];
message[7] = CRC[1];
}
}
This is my function number 3:
public bool SendFunc(int funcNumer, string connectType, byte address, ushort start, ushort registers, ref short[] values)
{
#region №3
if (funcNumer == 3)
{
#region serial-port
if (connectType.Equals("COM"))
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Function 3 request is always 8 bytes:
byte[] message = new byte[8];
//Function 3 response buffer:
byte[] response = new byte[5 + 2 * registers];
//Build outgoing modbus message:
BuildMessage(address, (byte)3, start, registers, ref message);
//Send modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse("COM", ref response);
}
catch (Exception err)
{
modbusStatus = "" + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
//Return requested register values:
for (int i = 0; i < (response.Length - 5) / 2; i++)
{
values[i] = response[2 * i + 3];
values[i] <<= 8;
values[i] += response[2 * i + 4];
}
modbusStatus = "";
return true;
}
else
{
modbusStatus = "";
return false;
}
}
else
{
modbusStatus = "";
return false;
}
}
And here I am trying to implement function number 6:
if (funcNumer == 6)
{
#region serial-port
if (connectType.Equals("COM"))
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Function 3 request is always 8 bytes:
byte[] message = new byte[8];
//Function 3 response buffer:
byte[] response = new byte[5 + 2 * registers];
//Build outgoing modbus message:
BuildMessage(address, (byte)6, start, registers, ref message);
//Send modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse("COM", ref response);
}
catch (Exception err)
{
modbusStatus = "" + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
//Return requested register values:
for (int i = 0; i < (response.Length - 5) / 2; i++)
{
values[i] = response[2 * i + 3];
values[i] <<= 8;
values[i] += response[2 * i + 4];
}
modbusStatus = "";
return true;
}
else
{
modbusStatus = "";
return false;
}
}
else
{
modbusStatus = "";
return false;
}
}
This is my function to check the response:
private bool CheckResponse(byte[] response)
{
//Perform a basic CRC check:
byte[] CRC = new byte[2];
GetCRC(response, ref CRC);
if (CRC[0] == response[response.Length - 2] && CRC[1] == response[response.Length - 1])
return true;
else
return false;
}
This is my function for get response:
private void GetResponse(string connect, ref byte[] response)
{
if (connect.Equals("COM"))
{
for (int i = 0; i < response.Length; i++)
{
response[i] = (byte)(sp.ReadByte());
}
}
else if (connect.Equals("TCP"))
{
NetworkStream stream = tcpClient.GetStream();
for (int i = 0; i < response.Length; i++)
{
response[i] = (byte)(stream.ReadByte());
}
}
else
{
}
}
The difference between Modbus function 0x03 and 0x06 is actually the part of the code you did not show on your question: CheckResponse(response).
Function 0x03 reads a number of registers, and the values in those registers (coming from the slave) are included in the response.
Function 0x06 writes a single register and gives an echo back. So the response is the same as the query.
With that information, it should be easy to modify your code: remove the for loop where you retrieve the register values.
Other than that you might need to modify your CheckResponse() function too, but that should also be quite straight forward: just check the response is exactly the same as the query (message).
EDIT: if your CheckResponse()` function only checks for the correct CRC on the responses I suppose you can keep it as it is.

How to send frames using User Datagram Protocol (UDP)

I have a device which i need to communicate to via host computer using C# and exchange frames between the device and host computer which are connected via Ethernet cable.The device has a port and ip which can be connected to.The following is sample code of frames communication between sender and receiver.
I have little knowledge in C# and i would like some help on how to establish the communication below using UDP protocol suite.Thanks
//Grab the data of the device
private byte[] Fetch_FrameID(bool bHostToDevice) //true:Host to Device false: Device to Host
{
return bHostToDevice ? new byte[] { 0x8F, 0xE1 } : new byte[] { 0x2D, 0x7A };
}
//Grab the Frame Sequence Number
private byte[] Fetch_FrameSequenceNumber(int iNumber)
{
return new byte[] { (byte)(iNumber & 0xFF), (byte)((iNumber >> 8) & 0xFF) };
}
//Grab the device status
private byte[] Fetch_HostToDeviceCommand(int iStatus) //status:0:Active 1:Sync 2:Request
{
switch (iStatus)
{
case 0: return new byte[] { 0x00, 0x00 }; //Active
case 1: return new byte[] { 0x11, 0x00 }; //Sync
case 2: return new byte[] { 0x21, 0x00 }; //Request
default: return null;
}
}
//Fetch Data Length
private byte[] Fetch_DataLen(byte[] dataArray)
{
int iLength = dataArray == null ? 0 : dataArray.Length;
return new byte[] { (byte)(iLength & 0xFF), (byte)((iLength >> 8) & 0xFF) };
}
//Fetch Data Check Sum
private byte[] Fetch_DataCheckSum(byte[] dataArray)
{
int iSum = 0;
if (dataArray != null)
{
for (int i = 0; i < dataArray.Length; i++)
{
iSum += (int)dataArray[i];
}
}
iSum += Convert.ToInt32("0xAA55", 16);
return new byte[] { (byte)(iSum & 0xFF), (byte)((iSum >> 8) & 0xFF) };
}
private byte[] Fetc_SendHeaderInfo(int iStatus, int iNumber, byte[] dataArray) //status:0:Active 1:Sync 2:Request
{
List<byte> result = new List<byte>();//TOTAL 12Bytes, each 2bytes
result.AddRange(Fetch_FrameID(true));//Grab FrameID
result.AddRange(Fetch_FrameSequenceNumber(iNumber));//Grab the FSN
result.AddRange(Fetch_HostToDeviceCommand(iStatus));//Grab host to device command
result.AddRange(Fetch_DataLen(dataArray));//Grab the data Length
result.AddRange(Fetch_DataCheckSum(dataArray)); //Grab the data Check sum
result.AddRange(Fetch_DataCheckSum(result.ToArray())); //Grab the headdata Check sum
return result.ToArray();
}
UDP and TCP are different protocols, in order to send UDP packets using .NET C# I suggest using UdpClient, here is a sample code for sending if that helps :
UdpClient udpClient = new UdpClient(ip, port);
try{
udpClient.Send(bytesToSend, bytesToSendLength);
}
catch ( Exception e ){
Console.WriteLine( e.ToString());
}
as for receiving you can use UdpClient.Receive
Here is Send & Receive documentation on MSDN

Migrating BCD conversion code from Java to .Net

I am converting a Java class that converts BCD data to ASCII
I am converting it to .Net BCD Convertor
Following is the converted from java but it is giving wrong converted value e.g. for 123456789 it is giving 123456153153
public static string GetStringFromBcd(int[] b)
{
StringBuilder buffer = new StringBuilder();
foreach (var t in b)
{
if ((t & 0x0000000F) == 0x0000000F && ((t >> 4) & 0x0000000F) == 0x0000000F)
{
break;
}
buffer.Append((t & 0x0000000F) + "");
if ((t & 0x000000F0) != 0x000000F0)
{
buffer.Append(((t >> 4) & 0x0000000F) + "");
}
}
}
What could be the problem?
EDIT: ANSWER:
I got the source program where the data has been BCD encoded.
I found that nothing was wrong in that logic, then I discovered the source of the function where the data was converting from network stream to string and later converted to byte/int array.
following is the code
int bytesRead = tcpClient.Receive(message);//, 0, bytetoReadSize);
if (bytesRead == 0)
{
break;
//the client has disconnected from the server
}
//message has successfully been received
data += new ASCIIEncoding().GetString(message, 0, bytesRead);
here is the problem ASCIIEncoding does not convert many encoded character and gives '?'63 instead of those character , when putting 63 in BCD conversion logic it gives 153.
To resolve this error, I Modified the last line and instead of decoding , I am simply casting the received byte to char.
foreach (byte b in message)
{
data += ((char) b);
}
Here's a Similar Question that comes about it a few different ways.
Here's a Site that has an excellent detailed description of what your facing.
It shouldn't be that hard, but processing them as int's is going to be much harder.
Zoned Decimal (BCD) is pretty straight forward to convert, but you have to be careful if your taking files from a mainframe that have been converted via an ASCII transfer. It can still be converted, but the byte values change due to the ebcdic to ascii conversion during the FTP.
If your processing binary files, it's much easier to deal with.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestZoned
{
class Program
{
public static String zoneToString(byte[] zoneBytes)
{
Encoding ascii = Encoding.ASCII;
Encoding ebcdic = Encoding.GetEncoding("IBM037");
byte[] asciiBytes = null;
String str = null;
int zoneLen = zoneBytes.Length;
int i = zoneLen - 1;
int b1 = zoneBytes[i];
b1 = (b1 & 0xf0) >> 4;
switch (b1)
{
case 13:
case 11:
zoneBytes[i] = (byte)(zoneBytes[i] | 0xf0);
asciiBytes = Encoding.Convert(ebcdic, ascii, zoneBytes);
str = "-" + ASCIIEncoding.ASCII.GetString(asciiBytes);
break;
default:
zoneBytes[i] = (byte)(zoneBytes[i] | 0xf0);
asciiBytes = Encoding.Convert(ebcdic, ascii, zoneBytes);
str = ASCIIEncoding.ASCII.GetString(asciiBytes);
break;
}
return (str);
}
static void Main(string[] args)
{
byte[] array = { 0xf0, 0xf0, 0xf1 }; // 001
byte[] pos = { 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; // 123456789
byte[] neg = { 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xd9 }; // -123456789
Console.WriteLine("Converted: {0}", zoneToString(array));
Console.WriteLine("Converted: {0}", zoneToString(pos));
Console.WriteLine("Converted: {0}", zoneToString(neg));
}
}
}
If you wanted to stick to something similar
public static String GetStringFromBcd(byte[] zoneBytes)
{
StringBuilder buffer = new StringBuilder();
int b1 = (zoneBytes[zoneBytes.Length - 1] & 0xf0) >> 4;
if ( (b1 == 13) || (b1 == 11) ) buffer.Append("-");
for (int i = 0; i < zoneBytes.Length; i++)
{
buffer.Append((zoneBytes[i] & 0x0f));
}
return buffer.ToString();
}

Categories