Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello everybody, I come up with a newbie question again. Well I need to convert integers INT to Byte types like 0x00 to 0xFF. I really dont know how to do this and wcan't find the info as well. If any of you know about this please help me.

Btw do I need to add an special header for converting
Posted
Updated 11-Oct-11 20:25pm
v2

1 solution

If you mean you wish to display an integer as a series of hex bytes, then you just need to use the %x or %X format specification[^] in a printf()[^] statement.

[edit]
That's fine then you just use a cast such as
C++
byte b = (byte)integerValue;

However for integer values greater than 255, you need to split the integer thus:
C++
for (int i = 3; i >= 0; ++i)
{
    byte b = (integervalue >> 8 * i) & 0xFF;
    send(b);
}

[/edit]
 
Share this answer
 
v2
Comments
GuSuB 12-Oct-11 12:58pm    
Thank you, but what I need is to change an INT variable into BYTE, I need this to fill an array<byte^> an send this array through serial port to my robot. I just need to change Type and send it on serial port.For example:

i have INT A=0, I need to send this as a Byte 0x00 in serial port
INT A=255 , send as Byte 0xFF..

I am a newbie yet. Thanks a lot
Richard MacCutchan 12-Oct-11 15:17pm    
See my edit entry above.
GuSuB 12-Oct-11 21:03pm    
HI thanks, you are right, I need to do some kind of casting but I tried the Cast and got this error message:

44 Error C2440: 'type cast': can not convert from 'int' to 'System:: Byte ^'

All my Integer values are lower than 255.
GuSuB 12-Oct-11 21:06pm    
This is how I am trying to cast:

Byte^ bdrh=(Byte^)DRh; where DRh is an int type
Richard MacCutchan 13-Oct-11 5:05am    
You are trying to cast to a reference rather than an element; it should be Byte bdrh = (Byte)DRh;. You can then pass the byte value bdrh into your array or whatever. Alternatively if you allocate your array first you can add the element directly by normal C++/CLI array referencing.

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