DataOutputStream.m 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // DataOutputStream.m
  3. // mtalk
  4. //
  5. // Created by maye on 13-10-24.
  6. // Copyright (c) 2013年 zuoye. All rights reserved.
  7. //
  8. #import "DataOutputStream.h"
  9. @implementation DataOutputStream
  10. - (id)init{
  11. self = [super init];
  12. if(self != nil){
  13. data = [[NSMutableData alloc] init];
  14. length = 0;
  15. }
  16. return self;
  17. }
  18. - (void)writeChar:(int8_t)v {
  19. int8_t ch[1];
  20. ch[0] = (v & 0x0ff);
  21. [data appendBytes:ch length:1];
  22. length++;
  23. }
  24. - (void)writeShort:(int16_t)v {
  25. int8_t ch[2];
  26. ch[0] = (v & 0x0ff00)>>8;
  27. ch[1] = (v & 0x0ff);
  28. [data appendBytes:ch length:2];
  29. length = length + 2;
  30. }
  31. - (void)writeInt:(int32_t)v {
  32. int8_t ch[4];
  33. for(int32_t i = 0;i<4;i++){
  34. ch[i] = ((v >> (i*8)) & 0x0ff);
  35. }
  36. [data appendBytes:ch length:4];
  37. length = length + 4;
  38. }
  39. - (void)writeLong:(int64_t)v {
  40. int8_t ch[8];
  41. for(int32_t i = 0;i<8;i++){
  42. ch[i] = ((v >> ((7 - i)*8)) & 0x0ff);
  43. }
  44. [data appendBytes:ch length:8];
  45. length = length + 8;
  46. }
  47. - (void)writeUTF:(NSString *)v {
  48. NSData *d = [v dataUsingEncoding:NSUTF8StringEncoding];
  49. uint32_t len = (uint32_t)[d length];
  50. [self writeInt:len];
  51. [data appendData:d];
  52. length = length + len;
  53. }
  54. - (void)writeBytes:(NSData *)v {
  55. int32_t len = (int32_t)[v length];
  56. [self writeInt:len];
  57. [data appendData:v];
  58. length = length + len;
  59. }
  60. -(void)writeDataCount
  61. {
  62. int8_t ch[4];
  63. for(int32_t i = 0;i<4;i++){
  64. ch[i] = ((length >> ((i)*8)) & 0x0ff);
  65. }
  66. [data replaceBytesInRange:NSMakeRange(0, 4) withBytes:ch];
  67. }
  68. - (NSMutableData *)toByteArray{
  69. return [[NSMutableData alloc] initWithData:data];
  70. }
  71. @end