-3

I have got an int array of "int word[10000]". i need a way such that 4 consecutive numbers corresponds to 1 element of an array. (byte addressing)

for example:

0, 1 , 2 , 3 refers to word[0]
4, 5 , 6 , 7 refers to word[1]
8 , 9 , 10 , 11 refers to word[2]
.....
396, 397, 398, 399 refers to word[100]

without using hash map or any other data structure.

Thanks

  • 7
    Did you try `index/4`? – Sergey Kalinichenko Mar 27 '17 at 09:45
  • Like a simple integer division? `0/4=1/4=2/4=3/4=0` and `4/4=5/4=6/4=7/4=1`, – Jonas Mar 27 '17 at 09:46
  • What is the *actual* problem you want to solve by this "byte addressing"? What are you actually trying to accomplish? – Some programmer dude Mar 27 '17 at 09:52
  • @Someprogrammerdude making a memory simulator in which i am storing 32 bit integer and i want to be able to store each byte separately in the word. – Hasnain Ali Mar 27 '17 at 09:54
  • Then you probably want to use *pointers* instead of simple division. Like e.g. `uint8_t* p = reinterpret_cast(word);` and then e.g. `p[0]` to get the first byte. It should not break strict aliasing since there are exceptions to allow it through pointers to `char`. – Some programmer dude Mar 27 '17 at 09:58
  • @Someprogrammerdude the aim is not to make a separate pointer for each byte because i want to make very big memory blocks. can i just use like: floor(byte address / 4) – Hasnain Ali Mar 27 '17 at 10:02
  • With a single `char` pointer to the whole `word` array, indexes `0`, `1`, `2` and `3` corresponds to `word[0]`. Indexes `4`, `5`, `6` and `7` corresponds to `word[1]`. Etc. Only one pointer needed. You should probably [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read up on pointers an arrays. – Some programmer dude Mar 27 '17 at 10:07

1 Answers1

1

Use

unsigned char *bytes=static_cast<unsigned char*>(word);
unsigned char first=bytes[0];
unsigned char second=bytes[1];

bytes will index through word as an array of 10000*sizeof(int) bytes though it appears you already know your platform has sizeof(int)==4.

NB 1: There's a rule that sizeof(unsigned char)==1. The best way to access bytes is usually through unsigned char.

NB 2: Whether your platform is big or little-endian will determine if bytes[0] is the least or most significant byte of the first element (and so on).

Persixty
  • 8,165
  • 2
  • 13
  • 35