Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,934 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,481 people online right now. Registration is fast and FREE... Join Now!




storing hex variables

 
Reply to this topicStart new topic

storing hex variables

tootypegs
1 Jan, 2008 - 04:18 PM
Post #1

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
Hi, my question lies with storing variables. In a file i have to value '02 00' in hex. I streamed through the file and assigned them to variables. However this is where im totally getting confused. Those hex values should give a decimal value of 512 but how to i combined the two bytes which i have stored in seperate variables as 1 decimal interger, not hex?

Is there a way to combined the 2 bytes of information and store them as one variable?

thanks
User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Storing Hex Variables
1 Jan, 2008 - 04:34 PM
Post #2

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
you can use them as Strings:

String hex = "02" + "00";
int decimal = Integer.parseInt(hex,16);
//decimal will hold 512 it will assume right most bits


Forget this, this is Java not C++, my bad tongue.gif
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Storing Hex Variables
1 Jan, 2008 - 04:37 PM
Post #3

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
Just looking for a little clarfication here...from the hex entry "02 00" you're extracting two variables, one storing "02" and one storing "00"? What data type are these variables stored as?

If you've got them stored in integer variables named, say, byte1 and byte2, combining the values into a single integer variable could be as simple as:
CODE
#include <iostream>

int main(){
    
    int byte1=0x02;
    int byte2=0x00;
    
    int total = 256 * byte1 + byte2;
    
    std::cout << total << std::endl;
    std::cout << std::hex << total << std::endl;
    
    return 0;
}

This is basically just manually performing a base-16 addition step to combine the two variables into a single value.

I think there may be a simpler way to do this using string streams - though this depends on the actual representation of the data in the file. Can you post a few lines from the file for us to look at? We might be able to come up with something a little more elegant than this.

But, of course, if the above works well enough for you, go for it smile.gif



QUOTE(William_Wilson @ 1 Jan, 2008 - 05:34 PM) *

you can use them as Strings:
CODE

String hex = "02" + "00";
int decimal = Integer.parseInt(hex,16);
//decimal will hold 512 it will assume right most bits



Wait a minute here...isn't that java?

This post has been edited by jjhaag: 1 Jan, 2008 - 04:37 PM
User is offlineProfile CardPM
+Quote Post

William_Wilson
RE: Storing Hex Variables
1 Jan, 2008 - 04:47 PM
Post #4

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
ya it is, my mistake, been coding a lot of Java today.
User is offlineProfile CardPM
+Quote Post

tootypegs
RE: Storing Hex Variables
1 Jan, 2008 - 04:52 PM
Post #5

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
thanks, just another quick question. These bytes could give values of 512, 1024, 2048 or 4096 i will not know the value so preforming manual calculations is something i would be unable to do....i think. I used those figures as an example. Say for instance i need those 2 bytes but i know not their values only that together they make a decimal number. So if i save those 2 bytes as

CODE

int byte1;
int byte2;

String hex = "byte1" + "byte2";


int decimal = Integer.parseInt(hex,16);



can it be coded like the above? sorry im unable to check as i dont have my compiler but i was hoping the logic was there

thanks

this is the first line in my file in hex view

eb58 904d 5344 4f53 352e 3002 0002
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Storing Hex Variables
1 Jan, 2008 - 06:10 PM
Post #6

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
That won't work in C++ because it's Java.

However, the code I posted above should allow you to do what you're looking for - the only reason that the variables were initialized to those specific values were for demonstration purposes, since those were what you posted and they had to have some value. That code should work for any given values that you've stored in the variables byte1 and byte2, regardless of how they got their values (initialized, streamed from file, etc).
User is offlineProfile CardPM
+Quote Post

tootypegs
RE: Storing Hex Variables
2 Jan, 2008 - 03:46 AM
Post #7

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
Ahhhhh thank you, i understand now it just took me a while!!!

but basically where you have

CODE

int byte1=0x02;
    int byte2=0x00;
    
    int total = 256 * byte1 + byte2;



I can have
CODE

int byte1;
int byte2;
    
int total = 256 * byte1 + byte2;


This way i can assign the variables whatever values happen to be in the file. Thanks for the help !
User is offlineProfile CardPM
+Quote Post

tootypegs
RE: Storing Hex Variables
3 Jan, 2008 - 09:50 AM
Post #8

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
Hi, sorry but my post is a slight variation of my last post. My aim is to store hex values in a variable where the hex value is more than 1 byte long. For example "40 23 03 00". This should be 205632 in decimal. At present i am collecting 1 byte at a time and storing it in a variable. However i cant get my head around how i can go about achieving this number. To add insult the hex is in little endian format so to get the decimal i need to reverse it to 00 03 23 40 then convert to decimal to achieve the correct number.

Ive tried to compile something that i thought might be along the correct lines below but im not having any joy with achieving the correct output, can anyone see where i might be going wrong? thanks

CODE



ifstream f ("c:\\test\\thumbdriveimage.txt",std::ios::binary);  
f.seekg (32,std::ios::beg);  

String SizeOfFile = "";

f.read (&SizeOfFile,sizeof (_32th));        
f.read (&SizeOfFile,sizeof (_33th));
f.read (&SizeOfFile,sizeof (_34th));
f.read (&SizeOfFile,sizeof (_35th));

int DECSizeOfFile =(int)SizeOfFile;



This post has been edited by tootypegs: 3 Jan, 2008 - 10:00 AM
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Storing Hex Variables
3 Jan, 2008 - 11:44 AM
Post #9

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
Are you dealing with fixed-length strings that encode for a given number? In your previous post you were talking about 2 single-byte values; now you've got 4. Which is it? Or are you dealing with variable length strings in the file? And are there spaces within the representation of a single number in the file? In the sample you provided, there are spaces and you say its in "hex view" - is that what it shows you in a hex editor, or is that the actual, exact physical representation in the file?

And I may be off base here, but I don't believe that you can use strings for file I/O in the way you are trying to - the read() method, at last check, only accepts a C-string, not an C++ STL string:
CODE
  #include <fstream>
  istream& read( char* buffer, streamsize num );


I'm going to hold off on posting anything more about an actual solution until there's a little more clarification - there's nothing here that looks especially complex, but a little more detail would make it way easier to specify a solution, without making it overly complex.
User is offlineProfile CardPM
+Quote Post

tootypegs
RE: Storing Hex Variables
3 Jan, 2008 - 11:56 AM
Post #10

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
hi sorry im going to try and clarify what im attempting. I am attempting to extract information from the boot sector of FAT 16. There are specific sections i am after that hold specific information, for example bytes 11-12 held bytes per sector but ive got this one sort. The one im now interested in is bytes 32-35 - number of sectors in file system and 22-23 - 16 bit integer for size of each FAT (u probs know all that anyway). Both of these are store little endian and need to be reversed for the true decimal value to be correct

Anyhow im just confusing my self all the time when trying to pull out the information. I have opened up my file in binary mode and extracted each byte and stored it separtely in an "unsigned char" which gives me the ascii representation of that byte (i think). If i take for example the bytes 22-23 i have them stored as below

unsigned char byte22;
unsigned char byte23;

before i convert to int i need somehow to swap the hex values into the correct format and concatonate them both then convert to dec?

I presume that is the process i would need to take but i am most likely wrong
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Storing Hex Variables
3 Jan, 2008 - 02:15 PM
Post #11

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
You're probably better off reading into a character array, rather than individual variables. It'll save you some steps, and also allow you to modular-ize your code a little more. To switch the endian-ness of the byte-representation you've read in, you would just need to perform a reversal of the array - check out the snippets section for either C or C++; both contain quite a number of string reversing techniques. But it's actually easier to use little-endian in this case (we'll see why in a moment).

As for actually extracting the proper value...

As with the previous snippet, the goal here is to manually add together the appropriately-based numbers. You're talking about hex, but that's just a way of representing individual bytes. So instead of thinking of this in hexadecimal, consider it in base-256 (a single 8-bit unit per byte instead of two 4-bit units, as you have with hexadecimal representation). The least-significant byte/character represent the number of ones; the next LS character represents the number of 256's; the next LS after that represents the number of 256x256=65536's, etc.

So your data in the file is given by "40 23 03 00" in little endian-format. That means you've got 0x40 (64 decimal) ones, 0x23 (35 decimal) 256's, and 0x03 (3 decimal). Multiplying each of those by the appropriate weights and adding:
CODE
64*1 + 35*256 + 3*65536 = 205632

gives you your answer.

Now to do this with your program, you simply multiply each character in sequence by an appropriate power of 256, and sum them. Here is where we see why dealing with the little-endian is a bit easier - you start with the power at 1, and run through each character in sequence, increasing the power by a factor of 256 after each step:
CODE
#include <iostream>

using namespace std;

int main() {
    
    char buffer[4]={0x40, 0x23, 0x03, 0x00};
    //example purposes only, this could be read in from the file
    //directly rather than initialized
    
    long result=0;
    long power=1;
    
    for (int i=0; i<4; ++i) {
        result+=buffer[i]*power;
        power*=256;
    }
    cout << result << endl;
    
    return 0;
}


There's probably (/definitely) a snazzier way to do this, but at least this way is (/should be) nice and clear. And if you were to convert that multiplication/addition loop into a function, where you pass an array and the number of elements, you wouldn't be restricted to using it for just a 4-character array.
User is offlineProfile CardPM
+Quote Post

tootypegs
RE: Storing Hex Variables
3 Jan, 2008 - 04:18 PM
Post #12

D.I.C Head
**

Joined: 9 Oct, 2007
Posts: 177


My Contributions
Thank you jjhaag you help has been much appreciated. I now have a better understanding and u'r help has allowed me to prgress!

cheers!
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 04:01PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month