Thread: unwanted sign extension

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    155

    unwanted sign extension

    i am trying to read from a binary file.

    hexcode of the binary:
    ff d8 ff d2 44 54 39 02 23 03 05

    Code:
    char buf[20];
    fread(buffer,sizeof(char),4,in);
    buf[0]=buf[0]&0xff;
    buf[1]=buf[1]&0xff;
    printf(" %x %x",buf[0],buf[1]);
    half the times i get this as teh out put:
    ff d8
    rest of teh times :
    ffffffff ffffffd8

    compiler i am using is dmc;

    i want the output to be consistently ff d8 all of the times.what do i need to do for that?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    printf("ff d8");

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    ok thats one way to do it.HIGHLY COMMENDABLE.


    what if i dont know what the first two bits r and still want the output to be consistent?**









    (**dont tell me i need to try out multiple times and then finally when i do have an idea of what the first 2 bits r i use printf( firstbit,secondbit) for consistency.)

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    try something along these lines:
    Code:
    char buf[20];
    fread(buffer,sizeof(char),4,in);
    int num1=buf[0]&0xff;
    int num2=buf[1]&0xff;
    printf(" %x %x",num1,num2);
    %x makes printf expect an int but you send a char....so you sent 3 bytes less than expected.

    Some speculations: because printf wants an int but gets a char, it will access some memory that hasnt been initiallized or is even used by you.
    STL Util a small headers-only library with various utility functions. Mainly for fun but feedback is welcome.

  5. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    i think that should help.
    thank you.

  6. #6
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Declare buf[] as unsigned char instead?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sign ' is the same as \' ?
    By George2 in forum C Programming
    Replies: 1
    Last Post: 11-23-2007, 07:32 AM
  2. My own itoa()
    By maxorator in forum C++ Programming
    Replies: 18
    Last Post: 10-15-2006, 11:49 AM
  3. Handle on MSN Messenger's Sign In "button"?
    By jmd15 in forum Windows Programming
    Replies: 3
    Last Post: 07-16-2005, 09:28 PM
  4. sign extension char
    By Laserve in forum C Programming
    Replies: 3
    Last Post: 04-28-2005, 08:28 AM
  5. Sign Up!: The Third Round, both contests
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 54
    Last Post: 07-20-2002, 05:46 PM