Click here to Skip to main content
Sign Up to vote bad
good
See more: MFCVC++
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
unsigned char data[1]. 
If for example if m_itemno is 12,then its hexadecimal equivalent is 0x0c
 
if I write unsigned
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 21 Jun '12 - 17:53
Edited 21 Jun '12 - 18:11


2 solutions

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:
 
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:
 
bool retval = WriteFile(hport,&m_itemno,1,&byteswritten,NULL);
  Permalink  
My problem got solved by using following code snippets
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);
}
  Permalink  
Comments
Jochen Arndt - 23 Jun '12 - 4:55
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)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 OriginalGriff 218
1 Sergey Alexandrovich Kryukov 159
2 Santhosh G_ 155
3 Richard MacCutchan 145
4 Maciej Los 136
0 Sergey Alexandrovich Kryukov 10,264
1 OriginalGriff 7,937
2 CPallini 4,201
3 Rohan Leuva 3,522
4 Maciej Los 3,135


Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 22 Jun 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid