-1

I have a short int, which is 2 bytes, but I only want to output the left byte to a file. How do I do this? I'm using binary functions open(), read(), write(), etc.

I would also like to shift the right byte to the left 8 times, so that the right byte occupies the left, and the right has been cleared to all 0's.

I apologize for not showing what I've already tried -- I'm a C noobie and cannot find anything about how to do this.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
user1472747
  • 529
  • 3
  • 10
  • 25
  • you''ll need to show some attempt... – Mitch Wheat Feb 16 '13 at 01:48
  • 2
    Read up on the bitwise operators, and _experiment_! You should also remember that the "left" and "right" side of a value depends much on the underlying platform (read about [endianess](http://en.wikipedia.org/wiki/Byte_order)). – Some programmer dude Feb 16 '13 at 01:51
  • Look at http://graphics.stanford.edu/~seander/bithacks.html for some inspiration. But _never_ forget that the occasional cost of a few microseconds of execution time is much, much less than a afternoon worth of head scratching because you don't understand anymore how the code works. Write the simplest code that does the job, check that it is standard conforming (your compiler and machine _will_ change!). Only start bumming when _measurements_ show it is worthwhile, and the compiler doesn't do it by itself. Organization and algorithms should be your first targets of scrutiny. – vonbrand Feb 16 '13 at 02:52
  • No. A short int is `sizeof (short int)` bytes. That value is not guaranteed to be 2. There are systems where sizeof (short int) == 1. @JoachimPileborg: Encouraging experimentation with regards to shifting negative integers is silly. Left shifting negative values is undefined behaviour, and right shifting might result in trap representations or exceptional conditions which according to 6.2.6.1p5 and 6.5p5 would also lead to undefined behaviour. – autistic Feb 16 '13 at 03:26

1 Answers1

2

You could try this approach

    int someNum = 0x1234;
    int  leftByte, rightByte;

    leftByte = (someNum >> 8) & 0xff;
    rightByte = (someNum) & 0xff;
Ganesh
  • 5,880
  • 2
  • 36
  • 54
  • Don't use shorts. They provide very little benefit. Use ints instead. http://stackoverflow.com/questions/13589183/is-the-performance-memory-benefit-of-short-nullified-by-downcasting/13589663#13589663 – SecurityMatt Feb 16 '13 at 03:05
  • Ok.. Thank you. I used `short int` to indicate a `16 bit` datatype as desired by user. I will modify my example to use `int` only – Ganesh Feb 16 '13 at 03:29
  • I suggest handling negative values separately to positive values. – autistic Feb 16 '13 at 03:34
  • @modifiablelvalue From the question, I presume the user is expecting to extract two 8-bit values from a 16-bit value similar to an unpack operation. Hence, I am not sure if the original question intended a sign handling also – Ganesh Feb 16 '13 at 03:37