FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Array of 4 bytes to int

 
Post new topic   Reply to topic     Forum Index -> General
View previous topic :: View next topic  
Author Message
TLukar



Joined: 26 Jan 2005
Posts: 2

PostPosted: Wed Jan 26, 2005 4:01 pm    Post subject: Array of 4 bytes to int Reply with quote

Hi does anyone know how can i convert from an array of 4 bytes to any other type, especialy int?

Or does anyone know where i can get the std.inbuffer D source file?
Back to top
View user's profile Send private message
JJR



Joined: 22 Feb 2004
Posts: 1104

PostPosted: Thu Jan 27, 2005 12:22 am    Post subject: Reply with quote

Well, I suppose you could do it much like C and use a union structure.

Of course the down and dirty method always works:

Code:
import std.stdio;

void main()
{
    byte[4] b32;
   
    b32[0]=2; // Low byte for little Endian, high for Big Endian
    b32[1]=4;
    b32[2]=8;
    b32[3]=6; // High byte for little Endian, low for Big Endian
   
    uint*   p32;
    uint    i32;

    // map the uint pointer to the byte array
    p32 = cast(uint*)&b32[0];
   
    // i32 can be assigned the value of the pointer
   
    i32 = *p32; 
   
    // The following could use *p32 or i32 to display the values
    // Display assuming little Endian (x86)

    printf("\n*p32 = ?lu \n", i32);
    printf("\nBYTE(4) of i32 = ?lu (HI)\n", i32 >> 24);
    printf("\nBYTE(3) of i32 = ?lu \n", (i32 & 0x00ffffff) >> 16);
    printf("\nBYTE(2) of i32 = ?lu \n", (i32 & 0x0000ffff) >> 8);
    printf("\nBYTE(1) of i32 = ?lu (LOW)\n", i32 & 0x000000ff);
    printf("\n*p32 = ?lu \n", *p32);
   
    // reassign new values
   
    b32[0] = 3;
    b32[1] = 4;
    b32[2] = 8;
    b32[3] = 2;
   
    i32 = *p32;
   
    // Or just use *p32 since it maps directly to the byte array.
}


Naturally, you have to adjust interpretation for platform endianness.

I'm not sure if that answers your question. I don't think D is much different than C or C++ in this regard.

There are other ways to do it too, I'm sure.

Later,

John R.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic     Forum Index -> General All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group