Converting from one data type to another

Hi All,

As a COBOL dinosaur from a more sequential world.....

(Yes.... we do still exist.... No we are not a figment of someones imagination used to frighten bold C++ programmers...!!!)

...I am very new to the whole C++ thing and my brain is begining to melt 'cause I can't figure how to convert from one data representation to another....

Here's the Problem...

I'm reading the content of a TIFF file into a dynamic character array (memblock) in memory.


I know where the control data used to format the image is held within the array and I need to format offset addresses within the file in order to access the image data.

Ex.: Bytes 4 to 7 contain an offset address. How do I get at this...??

I've been able to extract the address, character by character, into a smaller character array but I'm stuck on how to access this as an integer.


char address[4];
int j=0;

for (int i=7;i>3;i--)
{
address[j] = memblock[i];
j++;
}

The backwards nature of this code is as a result of the data in memory being in Little Endian format and I'm reversing it to get the correct address (I think..!).

I hope I've posted this to the correct forum and any help would be GREATLY appreciated....!!!!
1. Use [code][/code] tags
2. You can cast it to an integer... Like:
1
2
3
4
5
6
7
8
9
10
11
int Result = 0;
char * address = &Result; // address's memory is now also the Result's memory
// Just make sure your integer's size is 4 times bigger than your char's size
// It should, but you was talking about endianness...
int j = 0;
for(int i = 7; i <= 3; i--)
{
  address[j] = memblock[i];
  j++;
}
// Done, Result already has the offset stored inside! 
Last edited on
closed account (zb0S216C)
oneillh wrote:
I am very new to the whole C++ thing and my brain is begining to melt 'cause I can't figure how to convert from one data representation to another....

There's 3 main ways to convert from 1 type to another[1]:

1) static_cast
2) C-Style ((TYPE)EXPRESSION)
3) Functional Notation (TYPE(EXPRESSION))

static_cast is the most modern, along with functional notation. All three are exemplified below, as well as a description of each.

1
2
3
4
5
6
7
8
9
// statc_cast:
int My_int(0);
double My_double(static_cast<double>(My_int));

// C-Style:
float My_float((float)My_int);

// Functional Notation:
long My_long(long(My_int));

References:
[1] http://www.cplusplus.com/doc/tutorial/typecasting/


Wazzak
Last edited on
The correct way to do this is using bitshifting, e.g.:

1
2
3
4
5
6
7
typedef unsigned char byte;
uint readLittleEndianBytes(const byte* address,int noBytes)
{
    uint val=0;
    for (int i=0;i<noBytes;i++)val|=address[i]<<(i*CHAR_BITS);
    return val;
}
Last edited on
Topic archived. No new replies allowed.