Click here to Skip to main content
15,892,839 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
CString itemno;

UpdateData(TRUE);

itemno.Format("%x",m_itemno);// here m_itemno is integer in range 0 to 100

int  len = itemno.GetLength();

if(len == 1)

itemno = "0x0" + itemno;

if(len == 2)

itemno = "0x" + itemno;



unsigned char data[1] = itemno; // Here I  get problem;

~~~code for CreateFile etc~~~

bool retval = WriteFile(hport,data,1,&byteswritten,NULL);

//I have to send only 1 byte of data

Now the problem I am facing is that I am unable to convert from CString to
C++
unsigned char data[1]. 

If for example if m_itemno is 12,then its hexadecimal equivalent is 0x0c

if I write unsigned
C++
char data[1] = {0x0c}
,everything works fine but it is like hardcoding

but I want it done programatically so that I can enter any number between o to 100;

How to do it ?
Posted
Updated 21-Jun-12 18:11pm
v2

You want to send a binary data byte containing a (decimal) number in the range of 0 to 100 (0x64). Your member variable m_itemno already contains this value. So you might use this:

C++
unsigned char data = static_cast<unsigned char>(m_itemno & 0xFF);
bool retval = WriteFile(hport,&data,1,&byteswritten,NULL);


Because Intel processors use Little-Endian byte order (least significant byte is stored at lowest address) you may even use:

C++
bool retval = WriteFile(hport,&m_itemno,1,&byteswritten,NULL);
 
Share this answer
 
v2
My problem got solved by using following code snippets
C#
CString Class::IntToHex(int* yourint)

{
unsigned char ch[1];
Cstring output;
memcpy(ch,yourint,sizeof(int));
retVal = WriteFile(hPort,ch,1,&byteswritten,NULL);
}

CString Class::FloatToHex(float* yourfloat)
{
unsigned char ch2[4];
Cstring output;

memcpy(ch2,yourfloat,sizeof(float));
retVal = WriteFile(hPort,ch2,4,&byteswritten,NULL);
}
 
Share this answer
 
v2
Comments
Jochen Arndt 23-Jun-12 4:55am    
Copying the binary data using memcpy is not necessary. Just pass them as they are to WriteFile:
WriteFile(hPort, yourint, 1, &byteswritten, NULL);
WriteFile(hPort, yourfloat, sizeof(float), &byteswritten, NULL);
Your code contains a buffer overrun in IntToHex when copying 4 bytes (sizeof(int)) to the buffer ch which has a size of 1. The only reason why your code does not crash is the existance of the unused local variable CString output that is overwritten by memcpy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900