Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binary/Char to Int/Long

Status
Not open for further replies.

TheObserver

Programmer
Mar 26, 2002
91
US
I have a character array that ultimately ends up with binary/character data in it. It is an array of four elements, and of course each element has eight bits in it.

So I have (for example):
char length[4];

and the data therein is:
length[0] = 00000000
length[1] = 00000000
length[2] = 00111111
length[3] = 01111100

Or, alternately, as characters:
length[0] = " "
length[1] = " "
length[2] = "?"
length[3] = "|"
when output to the console.

I need to convert these into a number, but not for each item, a number made up of all of the array elements (4) that is 32 bits wide, thus:
00000000000000000011111101111100

and then convert that into an int or a long.

I know about atoi, atol, etc, but they only work on numeric or alphanumeric characters, and as you can see above, I definately would need to plan on not receiving alphanumeric characters.

I've looked all over and haven't found anything. Attempts to do this on my own have been unsuccessful. Any input on this matter would be very much appreciated.

Thanks for your time.
 
struct q32{

union{
struct{
char [4];
} str;
unsigned long q;
} quad;
};

don't forget endian byte order considerations

Hope that helps
-pete
 
Pardon my novice question, but I am kinda "reintroducing" myself to C/C++, but how would I go about using that struct to do what I need?

 
On the bright side, endianism should not be a problem when going from char to long. No byteswapping is performed on characters. However, use of memset would be useful. Remember, that 4 characters as a long will be a value, but 4 characters as a string will not have a null terminator and you will have issues printing it out. SOmething as simple as

long myLong;
memcpy(&myLong,charArray,sizeof(long));

will copy it into the long and then outputting as binary can be done in a for loop (there is an eample of this in one of the c/c++ forums)

Matt
 
opps sorry for the typeo, should be

struct q32{

union{
struct{
char c[4];
} str;
unsigned long q;
} quad;
};

struct q32 mylong;
memset( &mylong, 0, sizeof( mylong));
mylong.quad.str.c [2] = '?';
mylong.quad.str.c[3] = '|';

cout << mylong.quad.q << endl;

-pete
 
Thank you both for your responses. I went with Zyrenthian's solutions, tho, because it was a little easier to implement.

I've been trying to point long/int pointers at that character array all morning. I've never heard of memcopy. Thanks for the info.

And again, thank you both for your help.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top