Click here to Skip to main content
12,690,140 members (31,293 online)
Rate this:
Please Sign up or sign in to vote.
See more: MFC VisualC++
CString itemno;


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 18:53pm
Updated 21-Jun-12 19:11pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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);
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

My problem got solved by using following code snippets
CString Class::IntToHex(int* yourint)

unsigned char ch[1];
Cstring output;
retVal = WriteFile(hPort,ch,1,&byteswritten,NULL);

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

retVal = WriteFile(hPort,ch2,4,&byteswritten,NULL);
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170117.1 | Last Updated 22 Jun 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100